Pointer Lock API

Cette fonction est expérimentale
Puisque cette fonction est toujours en développement dans certains navigateurs, veuillez consulter le tableau de compatibilité pour les préfixes à utiliser selon les navigateurs.
Il convient de noter qu'une fonctionnalité expérimentale peut voir sa syntaxe ou son comportement modifié dans le futur en fonction des évolutions de la spécification.

Pointer lock (précedement appelé mouse lock) permet d'obtenir des informations sur le déplacement de la souris par rapport au temps écoulé (autrement dit les deltas) et ne se cantonne donc pas seulement à la position absolue du curseur sur l'écran. Cette interface confère l'accès aux données brutes de la souris, permet de verrouiller la cible des évènements à un élément unique, retire les limites de distance dans une direction donnée et cache le curseur.

Cette API est utile pour les applications qui ont besoin d'être attentives aux infos renvoyées par la souris afin de controler des mouvements ou faire pivoter des objets sur leurs axes.

Les jeux 3D de type FPS (First Person Shooter), les outils de modelisation, les vidéos immersives ou encore les cartes satellites sont autant de candidats idéals. L'utilisateur peut en effet changer l'angle de vue en bougeant simplement sa souris et sans cliquer sur aucun bouton ce qui les laisse donc disponibles pour effectuer d'autres actions.

Comme Pointer lock continue de déclencher des évènements même quand le curseur est en dehors des limites du navigateur ou de l'écran, cela résoud les inconvénients précédents où l'utilisateur devait faire attention de ne pas cliquer par inadvertance sur une autre fenêtre.

Concepts de base

Pointer Lock partage des similtudes avec mouse capture. Mouse capture offre un flot ininterrompu d'évènements sur un élément cible quand la souris glisse mais s'arrete quand le bouton est relaché. Pour cette raison, Pointer lock diffère de la capture de souris sur les points suivants :

  • Persistance. Pointer lock ne libère pas la souris tant qu'un appel explicite à l'API n'ait été effectué ou que l'utilisateur face un mouvement spécial.
  • Ne se limite pas aux bordures du navigateur ou de l'écran.
  • Continue de déclencher des évènements peu importe l'état des boutons de la souris.
  • Cache le curseur.

Exemple

Le code qui suit présente comment mettre en place Pointer Lock dans une page web.

<button onclick="lockPointer();">Lock it!</button>
<div id="pointer-lock-element"></div>
<script>
// Note: at the time of writing, only Mozilla and WebKit support Pointer Lock.

// The element we'll make fullscreen and pointer locked.
var elem;

document.addEventListener("mousemove", function(e) {
  var movementX = e.movementX       ||
                  e.mozMovementX    ||
                  e.webkitMovementX ||
                  0,
      movementY = e.movementY       ||
                  e.mozMovementY    ||
                  e.webkitMovementY ||
                  0;

  // Print the mouse movement delta values
  console.log("movementX=" + movementX, "movementY=" + movementY);
}, false);

function fullscreenChange() {
  if (document.webkitFullscreenElement === elem ||
      document.mozFullscreenElement === elem ||
      document.mozFullScreenElement === elem) { // Older API upper case 'S'.
    // Element is fullscreen, now we can request pointer lock
    elem.requestPointerLock = elem.requestPointerLock    ||
                              elem.mozRequestPointerLock ||
                              elem.webkitRequestPointerLock;
    elem.requestPointerLock();
  }
}

document.addEventListener('fullscreenchange', fullscreenChange, false);
document.addEventListener('mozfullscreenchange', fullscreenChange, false);
document.addEventListener('webkitfullscreenchange', fullscreenChange, false);

function pointerLockChange() {
  if (document.mozPointerLockElement === elem ||
      document.webkitPointerLockElement === elem) {
    console.log("Pointer Lock was successful.");
  } else {
    console.log("Pointer Lock was lost.");
  }
}

document.addEventListener('pointerlockchange', pointerLockChange, false);
document.addEventListener('mozpointerlockchange', pointerLockChange, false);
document.addEventListener('webkitpointerlockchange', pointerLockChange, false);

function pointerLockError() {
  console.log("Error while locking pointer.");
}

document.addEventListener('pointerlockerror', pointerLockError, false);
document.addEventListener('mozpointerlockerror', pointerLockError, false);
document.addEventListener('webkitpointerlockerror', pointerLockError, false);

function lockPointer() {
  elem = document.getElementById("pointer-lock-element");
  // Start by going fullscreen with the element.  Current implementations
  // require the element to be in fullscreen before requesting pointer
  // lock--something that will likely change in the future.
  elem.requestFullscreen = elem.requestFullscreen    ||
                           elem.mozRequestFullscreen ||
                           elem.mozRequestFullScreen || // Older API upper case 'S'.
                           elem.webkitRequestFullscreen;
  elem.requestFullscreen();
}
</script>

Method/properties overview

The Pointer lock API, similar to the Fullscreen API, extends DOM elements by adding a new method, requestPointerLock, which is vendor-prefixed for now. You write it as follows:

element.webkitRequestPointerLock(); // Chrome

element.mozRequestPointerLock(); // Firefox

Current implementations of requestPointerLock are tightly bound to requestFullScreen and the Fullscreen API. Before an element can be pointer locked, it must first enter the fullscreen state. As demonstrated above, the process of locking the pointer is asynchronous, with events (pointerlockchange, pointerlockerror) indicating the success or failure of the request. This matches how the Fullscreen API works, with its requestFullScreen method and fullscreenchange and fullscreenerror events.

The Pointer lock API also extends the document interface, adding both a new property and a new method. The new property is used for accessing the currently locked element (if any), and is named pointerLockElement, which is vendor-prefixed for now. The new method on document is exitPointerLock and, as the name implies, it is used to exit Pointer lock.

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 both uses:

document.pointerLockElement = document.pointerLockElement    ||
                              document.mozPointerLockElement ||
                              document.webkitPointerLockElement;

// 1) Used as a boolean check--are we pointer locked?
if (!!document.pointerLockElement) {
  // pointer is locked
} else {
  // pointer is not locked
}

// 2) Used to access the pointer locked element
if (document.pointerLockElement === someElement) {
  // someElement is currently pointer locked
}

The document's exitPointerLock method is used to exit pointer lock, and like requestPointerLock, works asynchrounously using the pointerlockchange and pointerlockerror events:

document.exitPointerLock = document.exitPointerLock    ||
                           document.mozExitPointerLock ||
                           document.webkitExitPointerLock;

function pointerLockChange() {
  document.pointerLockElement = document.pointerLockElement    ||
                                document.mozPointerLockElement ||
                                document.webkitPointerLockElement;

  if (!!document.pointerLockElement) {
    console.log("Still locked.");
  } else {
    console.log("Exited lock.");
  }
}

document.addEventListener('pointerlockchange', pointerLockChange, false);
document.addEventListener('mozpointerlockchange', pointerLockChange, false);
document.addEventListener('webkitpointerlockchange', pointerLockChange, false);

// Attempt to unlock
document.exitPointerLock();

pointerlockchange event

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

This event is currently prefixed as mozpointerlockchange in Firefox and webkitpointerlockchange in Chrome. 

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 and contains no extra data.

This event is currently prefixed as mozpointerlockerror in Firefox and webkitpointerlockerror in Chrome. 

Extensions to mouse events

The Pointer lock API extends the normal MouseEvent with movement attributes.

partial interface MouseEvent {
    readonly attribute long movementX;
    readonly attribute long movementY;
};
The movement attributes are currently prefixed as .mozMovementX and .mozMovementY in Firefox, and.webkitMovementX and .webkitMovementY in Chrome.

Two new parameters 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.

iframe limitations

Pointer lock can only lock one iframe at a time. If you lock one iframe, you cannot try to lock another iframe 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 iframes work by default, "sandboxed" iframes block Pointer lock. The ability to avoid this limitation, in the form of the attribute/value combination <iframe sandbox="allow-pointer-lock">, is expected to appear in Chrome soon.

Spécifications

Specification Etat Commentaire
Pointer Lock Working Draft Initial specification.

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support

Targeting 23webkit*

See CR/72574

14.0 (14.0)

bug 633602

Pas de support Pas de support Pas de support
Feature Android Firefox Mobile (Gecko) IE Phone Opera Mobile Safari Mobile
Basic support Pas de support Pas de support Pas de support Pas de support Pas de support

* Requires the feature be enabled in about:flags or Chrome started with the --enable-pointer-lock flag.

Voir aussi

MouseEvent

Étiquettes et contributeurs liés au document

Contributeurs ayant participé à cette page : Delapouite
Dernière mise à jour par : Delapouite,