I know how to track mouse movements when it is moving over the canvas area.
var canvas = document.getElementById("canvas");
var info = document.getElementById("info");
function getMovements(e) {
info.innerHTML = "x change: " + String(e.movementX) + " , y change: " + String(e.movementY);
}
canvas.addEventListener("mousemove", getMovements);
canvas {
background-color:bisque;
}
<canvas id ="canvas" width=300, height=300></canvas>
<div id=info></div>
But how can I do same thing with canvas.addEventListener("touchmove", getMovements);
event, when e.movementX
& e.movementY
doesnt work?
There are no such properties because a touch event can have multiple touches. You can however add these properties to the touchevent yourself before calling your getMovements
function.
var previousTouch;
canvas.addEventListener("touchmove", (e) => {
const touch = e.touches[0];
if (previousTouch) {
// be aware that these only store the movement of the first touch in the touches array
e.movementX = touch.pageX - previousTouch.pageX;
e.movementY = touch.pageY - previousTouch.pageY;
getMovements(e);
};
previousTouch = touch;
});
If you want to you can set the previousTouch
to null in the touchend
event to prevent a new touch to use the old previousTouch
on it's first move.
canvas.addEventListener("touchend", (e) => {
previousTouch = null;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With