Supporting Touch Interface in a canvas

本秂侑毒 提交于 2020-01-25 06:43:08

问题


I use a canvas, in which I support mouse dragging by setting in Javascript:

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

This works.. I can support drag operations with the mouse.

On iOS safari browser, though, dragging with a finger does not trigger the mouse functions.

Instead, the entire webpage just scrolls up or down.

At first I thought adding ontouchmove and others, would fix this. But it does not.

How can the browser on a mobile device tell when touches are meant for the canvas, and when for the browser it self?

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

回答1:


There is touchstart, touchmove, and touchend. If you want the browser to not respond itself to touch events then you need to tell it to not respond them. You do that by using addEventListener instead of ontouchstart and passing {passive: false} as the last argument. Otherwise the browser doesn't wait for JavaScript before responding to the touch events. You then call preventDefault on the event object passed to the handler to tell the browser not to do the normal thing (scroll the window)

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>

note the spacing is there to make sure there's enough space the window would scroll if you dragged your finger to show it doesn't scroll when you drag on the canvas. The meta tag is there so the browser, on mobile, shows a more mobile friendly scale.



来源:https://stackoverflow.com/questions/58908313/supporting-touch-interface-in-a-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!