Use Pointer Lock for infinite mouse movement
Mouse events are a great way to handle precise movement of the mouse. But the movement is constrained by the screen and may not go out of the window, constraining the possible movement.
Mainly for graphical applications (and FPS games), it's better to provide infinite movement. And this is where the Pointer Lock API comes into play.
When you have a lock, the mouse is frozen, but moving it still fires the events with movementX
and movementY
properties. You can then use these diffs to handle movement.
To request a Pointer Lock, you'll need an element, and then call the requestPointerLock
:
element.requestPointerLock();
And to get notified of pointer lock changes, add an event listener to the document:
document.addEventListener('pointerlockchange', () => {
// lock changed
}, false);
You can then subscribe to mouse events to handle the movements.
Why an element?
I couldn't find any references why an element is needed to grab a pointer lock. The best reason I could come up is to detect which code requested the lock:
document.addEventListener('pointerlockchange', () => {
if (document.pointerLockElement === element) {
// lock grabbed
}
}, false);
element.requestPointerLock();