Supporting Touch Interface In A Canvas
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
Solution 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);
functionhandleTouchStart(e) {
e.preventDefault();
}
functionhandleTouchMove(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;
}
<metaname="viewport"content="width=device-width, initial-scale=1.0, user-scalable=yes"><h1>spacing</h1><canvaswidth="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.
Post a Comment for "Supporting Touch Interface In A Canvas"