Javascript 使用 JS 跟踪鼠标速度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6417036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:38:50  来源:igfitidea点击:

Track mouse speed with JS

javascriptperformancemouse

提问by dandoen

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

使用普通 JS/JQuery 跟踪鼠标速度的最佳方法是什么?我想跟踪用户在各个方向(上/下/左/右)移动鼠标的速度。

采纳答案by Jonathan

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

Sparklines 有一个很好的例子来跟踪鼠标移动并绘制它。他们的代码可以在他们网站的源代码中找到,从第 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;
 });

回答by Niloy

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;
});

回答by Connor Smith

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.

每当鼠标移动时获取鼠标坐标。

回答by wazzaday

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.

在此示例中,我仅使用 touchX 完成了此操作。这个想法是每 200 毫秒拍摄一次 x 位置的快照,然后从当前位置获取快照,然后除以 200(速度 = 距离/时间)。这将保持速度的最新更新。时间为毫秒,输出将是每 200 毫秒行进的像素数。

回答by StefansArya

With current modern browser we can now use movementXor movementYto detect mouse's movement speed. Before you want to use it you should see the compatibility table because older browser will have a prefix like webkitMovementX.

使用当前的现代浏览器,我们现在可以使用moveXmoveY来检测鼠标的移动速度。在您想使用它之前,您应该查看兼容性表,因为较旧的浏览器将具有类似webkitMovementX.

document.addEventListener("mousemove", function(ev){
    console.log(`Movement X: ${ev.movementX}, Y: ${ev.movementY}`);
}, false);

The result above is not an average speed like pixel/second but it's total movement between triggered mousemoveevent. If you need px/sthen you can do it like below:

上面的结果不是像像素/秒这样的平均速度,而是触发mousemove事件之间的总移动。如果你需要,px/s那么你可以像下面这样做:

var totalX = 0;
var totalY = 0;
var moveX = 0;
var moveY = 0;

document.addEventListener("mousemove", function(ev){
    totalX += Math.abs(ev.movementX);
    totalY += Math.abs(ev.movementY);
    moveX += ev.movementX;
    moveY += ev.movementY;
}, false);

setInterval(function(){
    console.log(`Speed X: ${totalX}px/s, Y: ${totalY}px/s`);
    console.log(`Movement X: ${moveX}px/s, Y: ${moveY}px/s`);
    moveX = moveY = totalX = totalY = 0;
}, 1000);

Negative number represent movement to the left or top, while positive represent movement to the bottom or right direction.

负数表示向左或顶部移动,而正数表示向底部或向右移动。