Please note, this is a STATIC archive of website developer.mozilla.org from November 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

API Pointer Lock

Esta tradução está incompleta. Ajude atraduzir este artigo.

A API Pointer Lock (anteriormente chamada de Mouse Lock API) fornece métodos de entrada com base no movimento do mouse (i.e., deltas), e não apenas a posição absoluta do cursor do mouse na viewport. Têm acesso ao movimento raw mouse, bloqueia o target de eventos de mouse para um único elemento, elimina limites sobre o quão longe o movimento do mouse pode ir em uma única direção e remove o cursor de vista. É ideal para jogos 3D em primeira pessoa.

Mais do que isso, a API é útil para todas as aplicações que exigem entrada significativa do mouse para controlar movimentos, girar objetos e alterar as entradas, por exemplo, permitindo aos usuários controlar o ângulo de visão simplesmente movendo o mouse ao redor, sem qualquer clique de botão. Os botões então são liberados para outras ações. Outros exemplos incluem aplicações para visualização de mapas ou imagens de satélite.

Pointer lock permite que você acesse os eventos do mouse, mesmo quando o cursor vai além do limite do navegador ou da tela. Por exemplo, os usuários podem continuar a rodar ou manipular um modelo 3D, movendo o mouse sem fim. Sem bloqueio do cursor, a rotação ou manipulação pára o momento em que o ponteiro atinge a borda do navegador ou na tela. Os jogadores podem agora clicar em botões e cursor do mouse, sem se preocupar em deixar área de jogo acidentalmente, clicando em outro aplicativo que levaria o foco do mouse longe do foco atual, o jogo.

Conceitos básicos

Pointer lock is related to mouse capture. Mouse 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 mouse capture in the following ways:

Pointer lock está relacionada com a captura do mouse, que, fornece a entrega contínua de eventos a um elemento de destino enquanto o mouse está sendo arrastado, mas ele pára quando o botão do mouse é liberado. Pointer lock é diferente de captura do mouse nas seguintes maneiras:

  • É persistente: o Pointer lock não liberar o mouse até que uma chamada de API seja feita ou o usuário utilize um gesto de lançamento específico.
  • Não está limitado pelo navegador ou pela tela.
  • Continua a enviar eventos independentemente do estado de botão do mouse.
  • Esconde o cursor.

Visão geral sobre métodos/propriedades

Breve descrição de cada propriedade e método relacionado com a especificação.

requestPointerLock()

A API Pointer lock, semelhante à Fullscreen API, estende elementos do DOM, adicionando um novo método requestPointerLock(). Como tem unprefixed recentemente, você teria que atualmente declará algo como isso, por exemplo, solicitar o Pointer lock sobre um elemento de tela. Veja como fazer:

canvas.requestPointerLock = canvas.requestPointerLock ||
                            canvas.mozRequestPointerLock;

canvas.requestPointerLock()

pointerLockElement and exitPointerLock()

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() and the new method on Document is exitPointerLock() and, as the name implies, it is used to exit the 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 using pointerLockElement:

if(document.pointerLockElement === canvas ||
  document.mozPointerLockElement === 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.

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

// 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.

if ("onpointerlockchange" in document) {
  document.addEventListener('pointerlockchange', lockChangeAlert, false);
} else if ("onmozpointerlockchange" in document) {
  document.addEventListener('mozpointerlockchange', lockChangeAlert, false);
}

function lockChangeAlert() {
  if(document.pointerLockElement === canvas ||
  document.mozPointerLockElement === 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 and contains no extra data.

document.addEventListener('pointerlockerror', lockError, false);
document.addEventListener('mozpointerlockerror', lockError, false);

function lockError(e) {
  alert("Pointer lock failed"); 
}
Note: The above events are currently prefixed with moz in Firefox. 

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 simple pointer lock demo to show you how to use it to set up a simple control system (see source code). The demo looks like this:

A red circle on top of a black background.

This demo uses JavaScript to draw a ball on top of an <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.

Set initial x and y positions on the canvas:

var x = 50;
var y = 50;

The canvasDraw() function draws the ball in the current x and y positions, but it 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.

function canvasDraw() {
  if(x > canvas.width+20) {
    x = 0;  
  }

  if(y > canvas.height+20) {
    y = 0;  
  }  

  if(x < -20) {
    x = canvas.width;  
  }

  if(y < -20) {
    y = canvas.height;  
  }

  ctx.fillStyle = "black";
  ctx.fillRect(0,0,canvas.width,canvas.height);
  ctx.fillStyle = "#f00";
 
  ctx.beginPath();
  ctx.arc(x,y,20,0,degToRad(360), true);
  ctx.fill();
}

The pointer lock methods are currently prefixed, so next we'll fork them for the different browser implementations.

canvas.requestPointerLock = canvas.requestPointerLock ||
           canvas.mozRequestPointerLock;
// pointer lock object forking for cross browser

document.exitPointerLock = document.exitPointerLock ||
         document.mozExitPointerLock;
//document.exitPointerLock();

Now we set up an event listener to run the requestPointerLock() method on the canvas when it is clicked, which initiates pointer lock.

canvas.onclick = function() {
  canvas.requestPointerLock();
}

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

// pointer lock event listener

// Hook pointer lock state change events for different browsers
document.addEventListener('pointerlockchange', lockChangeAlert, false);
document.addEventListener('mozpointerlockchange', lockChangeAlert, false);

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

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

A tracker is set up to write out the X and Y values to the screen, for reference.

  var tracker = document.createElement('p');
  var body = document.querySelector('body');
  body.appendChild(tracker);
  tracker.style.position = 'absolute';
  tracker.style.top = '0';
  tracker.style.right = '10px';
  tracker.style.backgroundColor = 'white';

The canvasLoop() function first forks the movementX and movementY properties, as they are also prefixed currently in some browsers. It then adds those property's values to x and y, and reruns canvasDraw() with those new values so the ball position is updated. Finally, we use requestAnimationFrame() to run the loop again and again.

function canvasLoop(e) {
  var movementX = e.movementX ||
      e.mozMovementX          ||
      0;

  var movementY = e.movementY ||
      e.mozMovementY      ||
      0;

  x += movementX;
  y += movementY;

  canvasDraw();

  var animation = requestAnimationFrame(canvasLoop);

  tracker.innerHTML = "X position: " + x + ', Y position: ' + y;
}

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.

Specifications

Specification Status Comment
Pointer Lock Candidate Recommendation Initial specification.

Browser compatibility

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

(Yes)

(Yes)

(Yes) -moz
50 (50)

Não suportado (Yes) Não suportado
Feature Android Firefox Mobile (Gecko) Firefox OS IE Phone Opera Mobile Safari Mobile
Basic support Não suportado Não suportado Não suportado Não suportado Não suportado Não suportado

See also

Etiquetas do documento e colaboradores

 Colaboradores desta página: ted_k
 Última atualização por: ted_k,