A convenience utility library to take over the mouse cursor ("pointer lock") in the browser with JavaScript

Mon, Aug 24, 2015 - 1:03am -- Isaac Sukin

Two years ago when I was writing my book about building 3D browser games, I was spending a lot of time writing first person games in JavaScript. First person games in particular involve a lot of fast, precise motion, which makes "pointer lock" essential. "Pointer lock" is when a program takes over the mouse cursor, tracking mouse movement on its own and displaying its own cursor if needed (usually locked to the middle of the screen, hence the name).

Then and now, only Chrome and Firefox support the JavaScript pointer lock API. They both use prefixed versions with slightly different semantics, which makes using the API a pain. That's why I wrote PointerLock.js, a small JavaScript library that simplifies the Pointer Lock API.

To use it, all you have to do is call PL.requestPointerLock(element, onEnter, onExit, onError); where element is the DOM element that should lock the pointer and the other parameters are optional event callbacks. Then, to track mouse movement:

document.addEventListener('mousemove', function(event) {
    moveCamera(event.movementX, event.movementY);
}, false);

Usually when you want to lock the pointer you'll also want to be in full screen mode, which is why PointerLock.js plays nice with BigScreen which similarly simplifies the browser APIs for entering full screen.

Get PointerLock.js on GitHub!