gpt4 book ai didi

javascript - 支持 Canvas 中的触摸界面

转载 作者:行者123 更新时间:2023-12-02 22:30:48 24 4
gpt4 key购买 nike

我使用的是canvas,通过在Javascript中设置支持鼠标拖动:

  • canvas.onmousedown
  • canvas.onmouseup
  • canvas.onmousemove

这有效..我可以支持用鼠标进行拖动操作。

但在 iOS safari 浏览器上,用手指拖动不会触发鼠标功能。

相反,整个网页只是向上或向下滚动。

起初我认为添加 ontouchmove 和其他内容可以解决这个问题。但事实并非如此。

移动设备上的浏览器如何判断触摸何时针对 Canvas ,何时针对浏览器本身?

canvas.ontouchmove = function(ev) {
var x = ev.touches[0].clientX;
var y = ev.touches[0].clientY;
if ( dragging) {
drag(canvas, x, y);
}
}

最佳答案

有 touchstart、touchmove 和 touchend。如果您希望浏览器不响应触摸事件,那么您需要告诉它不响应它们。您可以通过使用 addEventListener 而不是 ontouchstart 并将 {passive: false} 作为最后一个参数传递来实现此目的。否则,浏览器在响应触摸事件之前不会等待 JavaScript。然后,您对传递给处理程序的事件对象调用 preventDefault 来告诉浏览器不要执行正常操作(滚动窗口)

const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');

canvas.addEventListener('touchstart', handleTouchStart, {passive: false});
canvas.addEventListener('touchmove', handleTouchMove);

function handleTouchStart(e) {
e.preventDefault();
}

function handleTouchMove(e) {
const rect = canvas.getBoundingClientRect();
const cssX = e.touches[0].clientX - rect.left;
const cssY = e.touches[0].clientY - rect.top;
const pixelX = cssX * canvas.width / rect.width;
const pixelY = cssY * canvas.height / rect.height;
ctx.fillStyle = `hsl(${performance.now() % 360 | 0},100%,50%)`;
ctx.fillRect(pixelX - 15, pixelY - 15, 30, 30);
}
canvas {
border: 1px solid black;
width: 300px;
height: 150px;
}
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">

<h1>spacing</h1>
<canvas width="600" height="300"></canvas>
<h1>spacing1</h1>
<h1>spacing2</h1>
<h1>spacing3</h1>
<h1>spacing4</h1>
<h1>spacing5</h1>
<h1>spacing6</h1>
<h1>spacing7</h1>
<h1>spacing8</h1>
<h1>spacing9</h1>
<h1>spacing10</h1>
<h1>spacing11</h1>
<h1>spacing12</h1>
<h1>spacing13</h1>
<h1>spacing14</h1>

请注意,间距是为了确保当您拖动手指时窗口有足够的空间可以滚动,以显示当您在 Canvas 上拖动时窗口不会滚动。元标记的存在使得移动设备上的浏览器显示出更适合移动设备的比例。

关于javascript - 支持 Canvas 中的触摸界面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58908313/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com