Track mouse speed with JS

前端 未结 5 1909
余生分开走
余生分开走 2020-12-23 19:07

What\'s the best way to track the mouse speed with plain JS/JQuery? I\'d like to track how fast a user moves the mouse in all directions (up/down/left/right).

5条回答
  •  一向
    一向 (楼主)
    2020-12-23 19:48

    This is a method to counter the fact you could start tracking, pause and then move your finger or mouse very quickly (suppose a sudden flick on a touch screen).

    var time = 200
    var tracker = setInterval(function(){
        historicTouchX = touchX;
    }, time);
    
    document.addEventListener("touchmove", function(){
        speed = (historicTouchX - touchX) / time;
        console.log(Math.abs(speed));
    }, false);
    

    I have done this with only the touchX in this example. The idea is to take a snapshot of the x position every 200 milliseconds, and then take that from the current position then divide by the 200 (speed = distance / time). This would keep a fresh update on the speed. The time is milliseconds and the output would be the number of pixels traveled per 200 milliseconds.

提交回复
热议问题