JavaScript MouseEvent.movementX and movementY large spikes
Asked Answered
D

0

10

After a pointer lock with Chrome, if you move the mouse, MouseEvent.movementX and MouseEvent.movementY will sometimes return a very large number that seems to be around half the size of the window.

Here is a minimal code example:

<html>
    <body>
        <canvas id="canvas" width="100" height="100" style="border: 1px solid">
        </canvas>
        <script>
            var canvas = document.getElementById("canvas");

            canvas.addEventListener("mousedown", function() {
                canvas.requestPointerLock();
            });

            document.addEventListener("mousemove", function() {
                if(Math.abs(event.movementX) > 100)
                    console.log(event.movementX);
            });
        </script>
    </body>
</html>

My hunch is that when you call requestPointerLock() it doesn't actually lock the mouse in one position, but just hides it. When the mouse goes off the window then it snaps the mouse back to the center which causes a large spike in the variable.

What is the cause of the large spike and how can I fix it?

Deathbed answered 27/12, 2017 at 3:6 Comment(9)
You mean you experience these spikes when moving slowly? You experience this issue only in chrome? I can get something like 800 when moving really fast, but that sounds accurate to my actual movements and it's the same in FF: I can not reproduce on chrome 63 on osX.Lacedaemon
@kaiido Yes, when moving slowly. It's definitely happening with me on chrome 63.Deathbed
Try on an other browser. If it also happens there, it might be related to your OS/device. Otherwise, file an issue to chromiumbugs.appspot.comLacedaemon
@Lacedaemon Tested it with Chrome, Firefox and Edge and it only happens with Chrome. Guess it's a bug with ChromeDeathbed
happens to me too, seems like on reaching the edge of the elementJemimah
Still happens on Chrome 81.Faintheart
Still happens in Chrome 103Coupler
Still happens in Chrome Version 111(.0.5563.64). But not if the DevTools is open, strangeMammet
Related: #48180412Pipes

© 2022 - 2025 — McMap. All rights reserved.