Pointer Lock API

Limited availability

This feature is not Baseline because it does not work in some of the most widely-used browsers.

The Pointer Lock API (formerly called Mouse Lock API) provides input methods based on the movement of the mouse over time (i.e., deltas), not just the absolute position of the mouse cursor in the viewport. It gives you access to raw mouse movement, locks the target of mouse events to a single element, eliminates limits on how far mouse movement can go in a single direction, and removes the cursor from view. It is ideal for first-person 3D games, for example.

More than that, the API is useful for any applications that require significant mouse input to control movements, rotate objects, and change entries, for example allowing users to control the viewing angle by moving the mouse around without any button clicking. The buttons are then freed up for other actions. Other examples include apps for viewing maps or satellite imagery.

Pointer lock lets you access mouse events even when the cursor goes past the boundary of the browser or screen. For example, your users can continue to rotate or manipulate a 3D model by moving the mouse without end. Without Pointer lock, the rotation or manipulation stops the moment the pointer reaches the edge of the browser or screen. Game players can now click buttons and swipe the mouse cursor back and forth without worrying about leaving the game play area and accidentally clicking another application that would take mouse focus away from the game.

Basic concepts

Pointer lock is related to pointer capture. Pointer capture provides continued delivery of events to a target element while a mouse is being dragged, but it stops when the mouse button is released. Pointer lock is different from pointer capture in the following ways:

  • It is persistent: Pointer lock does not release the mouse until an explicit API call is made or the user uses a specific release gesture.
  • It is not limited by browser or screen boundaries.
  • It continues to send events regardless of mouse button state.
  • It hides the cursor.

Method/properties overview

This section provides a brief description of each property and method related to the pointer lock specification.

requestPointerLock()

The Pointer lock API, similar to the Fullscreen API, extends DOM elements by adding a new method, requestPointerLock(). The following example requests pointer lock on a <canvas> element:

js
canvas.addEventListener("click", async () => {
  await canvas.requestPointerLock();
});

Note: If a user has exited pointer lock via the default unlock gesture, or pointer lock has not previously been entered for this document, an event generated as a result of an engagement gesture must be received by the document before requestPointerLock will succeed. (from https://w3c.github.io/pointerlock/#extensions-to-the-element-interface)

Operating systems enable mouse acceleration by default, which is useful when you sometimes want slow precise movement (think about you might use a graphics package), but also want to move great distances with a faster mouse movement (think about scrolling, and selecting several files). For some first-person perspective games however, raw mouse input data is preferred for controlling camera rotation — where the same distance movement, fast or slow, results in the same rotation. This results in a better gaming experience and higher accuracy, according to professional gamers.

To disable OS-level mouse acceleration and access raw mouse input, you can set the unadjustedMovement to true:

js
canvas.addEventListener("click", async () => {
  await canvas.requestPointerLock({
    unadjustedMovement: true,
  });
});

Handling promise and non-promise versions of requestPointerLock()

The above code snippet will still work in browsers that do not support the promise-based version of requestPointerLock() or the unadjustedMovement option — the await operator is permitted in front of a function that does not return a promise, and the options object will just be ignored in non-supporting browsers.

However, this could be confusing, and has other potential side-effects (for example, trying to use requestPointerLock().then() would throw an error in non-supporting browsers), so you may want to handle this explicitly using code along the following lines:

js
function requestPointerLockWithUnadjustedMovement() {
  const promise = myTargetElement.requestPointerLock({
    unadjustedMovement: true,
  });

  if (!promise) {
    console.log("disabling mouse acceleration is not supported");
    return;
  }

  return promise
    .then(() => console.log("pointer is locked"))
    .catch((error) => {
      if (error.name === "NotSupportedError") {
        // Some platforms may not support unadjusted movement.
        // You can request again a regular pointer lock.
        return myTargetElement.requestPointerLock();
      }
    });
}

pointerLockElement and exitPointerLock()

The Pointer lock API also extends the Document interface, adding a new property and a new method:

The pointerLockElement property is useful for determining if any element is currently pointer locked (e.g., for doing a boolean check) and also for obtaining a reference to the locked element, if any.

Here is an example of using pointerLockElement:

js
if (document.pointerLockElement === canvas) {
  console.log("The pointer lock status is now locked");
} else {
  console.log("The pointer lock status is now unlocked");
}

The Document.exitPointerLock() method is used to exit pointer lock, and like requestPointerLock, works asynchronously using the pointerlockchange and pointerlockerror events, which you'll see more about below.

js
document.exitPointerLock();

pointerlockchange event

When the Pointer lock state changes—for example, when calling requestPointerLock() or exitPointerLock(), the user pressing the ESC key, etc.—the pointerlockchange event is dispatched to the document. This is a simple event containing no extra data.

js
document.addEventListener("pointerlockchange", lockChangeAlert);

function lockChangeAlert() {
  if (document.pointerLockElement === canvas) {
    console.log("The pointer lock status is now locked");
    // Do something useful in response
  } else {
    console.log("The pointer lock status is now unlocked");
    // Do something useful in response
  }
}

pointerlockerror event

When there is an error caused by calling requestPointerLock() or exitPointerLock(), the pointerlockerror event is dispatched to the document. This is a simple event containing no extra data.

js
document.addEventListener("pointerlockerror", lockError);

function lockError(e) {
  alert("Pointer lock failed");
}

Extensions to mouse events

The Pointer lock API extends the normal MouseEvent interface with movement attributes. Two new attributes to mouse events—movementX and movementY—provide the change in mouse positions. The values of the parameters are the same as the difference between the values of MouseEvent properties, screenX and screenY, which are stored in two subsequent mousemove events, eNow and ePrevious. In other words, the Pointer lock parameter movementX = eNow.screenX - ePrevious.screenX.

Locked state

When Pointer lock is enabled, the standard MouseEvent properties clientX, clientY, screenX, and screenY are held constant, as if the mouse is not moving. The movementX and movementY properties continue to provide the mouse's change in position. There is no limit to movementX and movementY values if the mouse is continuously moving in a single direction. The concept of the mouse cursor does not exist and the cursor cannot move off the window or be clamped by a screen edge.

Unlocked state

The parameters movementX and movementY are valid regardless of the mouse lock state, and are available even when unlocked for convenience.

When the mouse is unlocked, the system cursor can exit and re-enter the browser window. If that happens, movementX and movementY could be set to zero.

Simple example walkthrough

We've written a pointer lock demo (see source code) to show you how to use it to set up a simple control system. This demo uses JavaScript to draw a ball on top of a <canvas> element. When you click the canvas, pointer lock is then used to remove the mouse pointer and allow you to move the ball directly using the mouse. Let's see how this works.

We set initial x and y positions on the canvas:

js
let x = 50;
let y = 50;

Next we set up an event listener to run the requestPointerLock() method on the canvas when it is clicked, which initiates pointer lock. The document.pointerLockElement check is to see if there is already an active pointer lock — we don't want to keep calling requestPointerLock() on the canvas every time we click inside it if we already have pointer lock.

js
canvas.addEventListener("click", async () => {
  if (!document.pointerLockElement) {
    await canvas.requestPointerLock({
      unadjustedMovement: true,
    });
  }
});

Note: The above snippet works in browsers that don't support the promise version of requestPointerLock(). See Handling promise and non-promise versions of requestPointerLock() for an explanation.

Now for the dedicated pointer lock event listener: pointerlockchange. When this occurs, we run a function called lockChangeAlert() to handle the change.

js
document.addEventListener("pointerlockchange", lockChangeAlert);

This function checks the pointerLockElement property to see if it is our canvas. If so, it attached an event listener to handle the mouse movements with the updatePosition() function. If not, it removes the event listener again.

js
function lockChangeAlert() {
  if (document.pointerLockElement === canvas) {
    console.log("The pointer lock status is now locked");
    document.addEventListener("mousemove", updatePosition);
  } else {
    console.log("The pointer lock status is now unlocked");
    document.removeEventListener("mousemove", updatePosition);
  }
}

The updatePosition() function updates the position of the ball on the canvas (x and y), and also includes if () statements to check whether the ball has gone off the edges of the canvas. If so, it makes the ball wrap around to the opposite edge. It also includes a check whether a requestAnimationFrame() call has previously been made, and if so, calls it again as required, and calls the canvasDraw() function that updates the canvas scene. A tracker is also set up to write out the X and Y values to the screen, for reference.

js
const tracker = document.getElementById("tracker");

let animation;
function updatePosition(e) {
  x += e.movementX;
  y += e.movementY;
  if (x > canvas.width + RADIUS) {
    x = -RADIUS;
  }
  if (y > canvas.height + RADIUS) {
    y = -RADIUS;
  }
  if (x < -RADIUS) {
    x = canvas.width + RADIUS;
  }
  if (y < -RADIUS) {
    y = canvas.height + RADIUS;
  }
  tracker.textContent = `X position: ${x}, Y position: ${y}`;

  animation ??= requestAnimationFrame(() => {
    animation = null;
    canvasDraw();
  });
}

The canvasDraw() function draws the ball in the current x and y positions:

js
function canvasDraw() {
  ctx.fillStyle = "black";
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = "red";
  ctx.beginPath();
  ctx.arc(x, y, RADIUS, 0, degToRad(360), true);
  ctx.fill();
}

IFrame limitations

Pointer lock can only lock one <iframe> at a time. If you lock one <iframe>, you can't lock another one and transfer the target to it; pointer lock will error out. To avoid this limitation, first unlock the locked <iframe>, and then lock the other.

While <iframe> work by default, "sandboxed" <iframe>s block Pointer lock. To avoid this limitation, use <iframe sandbox="allow-pointer-lock">.

Specifications

Specification
Pointer Lock 2.0

Browser compatibility

api.Document.exitPointerLock

desktop mobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
exitPointerLock
Chrome – Full support
Chrome 22 (Release date: 2012-09-25)
prefix
prefix Implemented with the vendor prefix: webkit
Chrome – Full support
Chrome 37 (Release date: 2014-08-26)
footnote Full support
Edge – Full support
Edge 13 (Release date: 2015-11-12)
footnote Full support
Firefox – No support
Firefox 14 – 49 (Release date: 2012-07-17)
prefix
prefix Implemented with the vendor prefix: moz
Firefox – Full support
Firefox 50 (Release date: 2016-11-15)
footnote Full support
Opera – Full support
Opera 15 (Release date: 2013-07-02)
prefix
prefix Implemented with the vendor prefix: webkit
Opera – Full support
Opera 24 (Release date: 2014-09-02)
footnote Full support
Safari – Full support
Safari 10.1 (Release date: 2017-03-27)
footnote Full support
Chrome Android – No support
Chrome Android
footnote
footnote See bug 40290045
Firefox for Android – No support
Firefox for Android 14 – 49 (Release date: 2012-06-26)
prefix
prefix Implemented with the vendor prefix: moz
Firefox for Android – Full support
Firefox for Android 50 (Release date: 2016-11-15)
footnote Full support
Opera Android – No support
Opera Android
footnote
footnote See bug 40290045
Safari on iOS – No support
Safari on iOS
footnote No support
Samsung Internet – No support
Samsung Internet
footnote
footnote See bug 40290045
WebView Android – No support
WebView Android
footnote
footnote See bug 40290045
WebView on iOS – No support
WebView on iOS
footnote No support

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
No support
No support
See implementation notes.
Requires a vendor prefix or different name for use.
Has more compatibility info.

api.Element.requestPointerLock

desktop mobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
requestPointerLock
Chrome – No support
Chrome 22 – 37 (Release date: 2012-09-25)
prefix
footnote Removed in 38 and later
prefix Implemented with the vendor prefix: webkit
Chrome – Full support
Chrome 37 (Release date: 2014-08-26)
footnote
footnote From version 92, returns a promise instead of undefined. The behavior reflects a specification change.
Edge – Full support
Edge 13 (Release date: 2015-11-12)
footnote
footnote From version 92, returns a promise instead of undefined. The behavior reflects a specification change.
Firefox – No support
Firefox 14 – 49 (Release date: 2012-07-17)
prefix
prefix Implemented with the vendor prefix: moz
Firefox – Full support
Firefox 50 (Release date: 2016-11-15)
footnote Full support
Opera – No support
Opera 15 – 24 (Release date: 2013-07-02)
prefix
footnote Removed in 25 and later
prefix Implemented with the vendor prefix: webkit
Opera – Full support
Opera 24 (Release date: 2014-09-02)
footnote
footnote From version 78, returns a promise instead of undefined. The behavior reflects a specification change.
Safari – Full support
Safari 10.1 (Release date: 2017-03-27)
footnote
footnote From version 18.4, returns a promise instead of undefined. The behavior reflects a specification change.
Chrome Android – No support
Chrome Android
footnote
footnote See bug 40290045
Firefox for Android – No support
Firefox for Android 14 – 49 (Release date: 2012-06-26)
prefix
prefix Implemented with the vendor prefix: moz
Firefox for Android – Full support
Firefox for Android 50 (Release date: 2016-11-15)
footnote Full support
Opera Android – No support
Opera Android
footnote
footnote See bug 40290045
Safari on iOS – No support
Safari on iOS
footnote No support
Samsung Internet – No support
Samsung Internet 1.5 – 2.1 (Release date: 2013-09-25)
prefix
prefix Implemented with the vendor prefix: webkit
Samsung Internet – Full support
Samsung Internet 3 (Release date: 2015-04-10)
footnote
footnote From version 16, returns a promise instead of undefined. The behavior reflects a specification change.
WebView Android – No support
WebView Android
footnote
footnote See bug 40290045
WebView on iOS – No support
WebView on iOS
footnote No support
options.unadjustedMovement parameter
Chrome – Full support
Chrome 88 (Release date: 2021-01-19)
footnote
footnote Supported on macOS Catalina 10.15.1+, Windows, and ChromeOS. Not yet supported on Linux.
Edge – Full support
Edge 88 (Release date: 2021-01-21)
footnote
footnote Supported on macOS Catalina 10.15.1+, Windows, and ChromeOS. Not yet supported on Linux.
Firefox – No support
Firefox
footnote No support
Opera – Full support
Opera 74 (Release date: 2021-02-02)
footnote
footnote Supported on macOS Catalina 10.15.1+, Windows, and ChromeOS. Not yet supported on Linux.
Safari – Full support
Safari 18.4 (Release date: 2025-03-31)
footnote Full support
Chrome Android – No support
Chrome Android
footnote
footnote See bug 40290045
Firefox for Android – No support
Firefox for Android
footnote No support
Opera Android – No support
Opera Android
footnote
footnote See bug 40290045
Safari on iOS – No support
Safari on iOS
footnote No support
Samsung Internet – No support
Samsung Internet
footnote
footnote See bug 40290045
WebView Android – No support
WebView Android
footnote
footnote See bug 40290045
WebView on iOS – No support
WebView on iOS
footnote No support

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
No support
No support
See implementation notes.
Requires a vendor prefix or different name for use.
Has more compatibility info.

See also