niloy / blog

blog raw files
3 stars 1 forks source link

Tracking mouse/flick speed #12

Open niloy opened 11 years ago

niloy commented 11 years ago

Tracking mouse/flick speed

Useful for implementing kinetic scrolling.

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;

    console.log([speedX, speedY]);
});