在画布中支持触摸界面

我使用的是画布,其中通过设置Javascript支持鼠标拖动:

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

这有效。我可以使用鼠标来支持拖动操作。

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

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

起初,我认为添加ontouchmove和其他名称将解决此问题。但事实并非如此。

移动设备上的浏览器如何分辨何时触摸画布,以及何时使浏览器自我触摸?

canvas.ontouchmove = function(ev) {
    var x = ev.touches[0].clientX;
    var y = ev.touches[0].clientY;
    if ( dragging) {
        drag(canvas,x,y);
    }
}
michelleyu7 回答:在画布中支持触摸界面

有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>

请注意是否有间距,以确保在您拖动手指时在画布上拖动时窗口将滚动,以显示窗口不会滚动。有了meta标签,因此在移动设备上的浏览器显示出更友好的移动比例。

本文链接:https://www.f2er.com/3083485.html

大家都在问