Track mouse speed with JS

ぃ、小莉子 提交于 2019-12-18 10:43:30

问题


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).


回答1:


Sparklines has a nifty example of tracking mouse movement and graphing it. Their code is available in the source of their site starting at line 315.

Simple and effective.

Here is the code:

 var mrefreshinterval = 500; // update display every 500ms
 var lastmousex=-1; 
 var lastmousey=-1;
 var lastmousetime;
 var mousetravel = 0;
 $('html').mousemove(function(e) {
     var mousex = e.pageX;
     var mousey = e.pageY;
     if (lastmousex > -1)
         mousetravel += Math.max( Math.abs(mousex-lastmousex), Math.abs(mousey-lastmousey) );
     lastmousex = mousex;
     lastmousey = mousey;
 });



回答2:


var timestamp = null;
var lastMouseX = null;
var lastMouseY = null;

document.body.addEventListener("mousemove", function(e) {
    if (timestamp === null) {
        timestamp = Date.now();
        lastMouseX = e.screenX;
        lastMouseY = e.screenY;
        return;
    }

    var now = Date.now();
    var dt =  now - timestamp;
    var dx = e.screenX - lastMouseX;
    var dy = e.screenY - lastMouseY;
    var speedX = Math.round(dx / dt * 100);
    var speedY = Math.round(dy / dt * 100);

    timestamp = now;
    lastMouseX = e.screenX;
    lastMouseY = e.screenY;
});



回答3:


Same way you get speed for anything else:

speed = distance / time

acceleration = speed / time 

And use:

 $(document).mousemove(function(e){
     var xcoord = e.pageX;
     var ycoord = e.pageY;
 }); 

To get the mouse coordinates whenever the mouse moves.




回答4:


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.



来源:https://stackoverflow.com/questions/6417036/track-mouse-speed-with-js

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