Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are movementX and movementY alternatives for touch events?

Tags:

javascript

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?

like image 884
WhoAmI Avatar asked Mar 02 '23 03:03

WhoAmI


1 Answers

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;
});
like image 177
swift-lynx Avatar answered Mar 05 '23 14:03

swift-lynx