Track mouse speed with JS

前端 未结 5 1892
余生分开走
余生分开走 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:51

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

提交回复
热议问题