Aiden
Aiden

Reputation: 399

Javascript mousemove event firing

Is there a way using mousemove event to capture every pixel that the cursor collides with? so that the following condition would fire consistently.

if(e.pageX == 100) 

I find that if the mouse moves fast then it skips pixels in between.. however if I move it slowly it will catch pixels one by one.

Thanks

Upvotes: 1

Views: 1017

Answers (2)

Flot2011
Flot2011

Reputation: 4671

Mousemove triggers on every mouse movement and targets the topmost and most nested element which is covered by mouse. Mousemove, mouseover and mouseout trigger when browser internal timing allows only. That means if you move the mouse fast, intermediate DOM elements and parents will be skipped.

So you can move over an element without any mousemove/mouseover triggered on it.

You also can move from a child through parent without any mouse event on the parent as browser skips intermediate elements

The only guarantee you have is that as far as mouseover was triggered, the mouseout will trigger too.

Upvotes: 2

6502
6502

Reputation: 114579

No.

Mouse cursor is checked and if the position has changed since last time a mousemove event is triggered, but only with the new detected position.

What you can do is storing the last known mouse position and the compute a straight line between that and the current position to do your computations. This doesn't require much code... a simple approach is

// Calls `f(x, y)` for each point starting from
// `(x0, y0)` and ending in `(x1, y1)` (excluded)
// moving along an 8-connected straight path.
function processLine(x0, y0, x1, y1, f) {
    var ix = x0 < x1 ? 1 : -1, dx = Math.abs(x1 - x0);
    var iy = y0 < y1 ? 1 : -1, dy = Math.abs(y1 - y0);
    var m = Math.max(dx, dy), cx = m >> 1, cy = m >> 1;
    for (var i=0; i<m; i++) {
        f(x0, y0);
        if ((cx += dx) >= m) { cx -= m; x0 += ix; }
        if ((cy += dy) >= m) { cy -= m; y0 += iy; }
    }
}

and can be used as

processLine(10, 20, 30, 35, function(x, y) {
    console.log("x=" + x + ", y=", y);
});

Upvotes: 0

Related Questions