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

Revision 1074384 of Pointer Lock API

  • Revision slug: Web/API/Pointer_Lock_API
  • Revision title: Pointer Lock API
  • Revision id: 1074384
  • Created:
  • Creator: chrisdavidmills
  • Is current revision? No
  • Comment

Revision Content

{{DefaultAPISidebar("Pointer Lock API")}}

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 simply 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 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:

  • 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, {{domxref("Element.requestPointerLock","requestPointerLock")}}, which is vendor-prefixed for now. You would currently declare it something like this, for example if you wanted to request pointer lock on a canvas element.:

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

canvas.requestPointerLock()

pointerLockElement and exitPointerLock()

The Pointer lock API also extends the {{domxref("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 {{domxref("Document.pointerLockElement","pointerLockElement")}}, which is vendor-prefixed for now. The new method on {{domxref("Document")}} is {{domxref("Document.exitPointerLock","exitPointerLock")}} and, as the name implies, it is used to exit Pointer lock.

The {{domxref("Document.pointerLockElement","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 {{domxref("Document.exitPointerLock")}} method is used to exit pointer lock, and like {{domxref("Element.requestPointerLock","requestPointerLock")}}, works asynchronously using the {{event("pointerlockchange")}} and {{event("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 {{domxref("Element.requestPointerLock","requestPointerLock")}}, {{domxref("Document.exitPointerLock","exitPointerLock")}}, the user pressing the ESC key, etc.—the {{event("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 {{domxref("Element.requestPointerLock","requestPointerLock")}} or {{domxref("Document.exitPointerLock","exitPointerLock")}}, the {{event("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 {{domxref("MouseEvent")}} interface 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.

Two new parameters to mouse events—{{domxref("MouseEvent.movementX","movementX")}} and {{domxref("MouseEvent.movementY","movementY")}}—provide the change in mouse positions. The values of the parameters are the same as the difference between the values of {{domxref("MouseEvent")}} properties, {{domxref("MouseEvent.screenX","screenX")}} and {{domxref("MouseEvent.screenY","screenY")}}, which are stored in two subsequent {{event("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 {{domxref("MouseEvent")}} properties {{domxref("MouseEvent.clientX","clientX")}}, {{domxref("MouseEvent.clientY","clientY")}}, {{domxref("MouseEvent.screenX","screenX")}}, and {{domxref("MouseEvent.screenY","screenY")}} are held constant, as if the mouse is not moving. The {{domxref("MouseEvent.movementX","movementX")}} and {{domxref("MouseEvent.movementY","movementY")}} properties continue to provide the mouse's change in position. There is no limit to {{domxref("MouseEvent.movementX","movementX")}} and {{domxref("MouseEvent.movementY","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 {{domxref("MouseEvent.movementX","movementX")}} and {{domxref("MouseEvent.movementY","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, {{domxref("MouseEvent.movementX","movementX")}} and {{domxref("MouseEvent.movementY","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 {{ htmlelement("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
{{SpecName('Pointer Lock')}} {{Spec2('Pointer Lock')}} Initial specification.

Browser compatibility

{{ CompatibilityTable() }}

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

Yes

Yes

Yes {{ property_prefix("gecko") }}

{{ CompatNo() }} Yes {{ CompatNo() }}
Feature Android Firefox Mobile (Gecko) Firefox OS IE Phone Opera Mobile Safari Mobile
Basic support {{ CompatNo() }} {{ CompatNo() }} {{ CompatNo() }} {{ CompatNo() }} {{ CompatNo() }} {{ CompatNo() }}

See also

  • {{domxref("MouseEvent")}}

Revision Source

<p>{{DefaultAPISidebar("Pointer Lock API")}}</p>

<p><span class="seoSummary">The <strong>Pointer Lock API</strong> (formerly called <em>Mouse Lock API</em>) 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.</span> It is ideal for first person 3D games, for example.</p>

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

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

<h2 id="basics" name="basics">Basic concepts</h2>

<p>Pointer lock is related to <a href="/en/DOM/element.setCapture" title="element.setCapture">mouse capture</a>. 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:</p>

<ul>
 <li>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.</li>
 <li>It is not limited by browser or screen boundaries.</li>
 <li>It continues to send events regardless of mouse button state.</li>
 <li>It hides the cursor.</li>
</ul>

<h2 id="method_overview" name="method_overview">Method/properties&nbsp;overview</h2>

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

<h3 id="requestPointerLock()">requestPointerLock()</h3>

<p>The Pointer lock API, similar to the <a href="/en-US/docs/Web/Guide/API/DOM/Using_full_screen_mode">Fullscreen API</a>, extends DOM elements by adding a new method, {{domxref("Element.requestPointerLock","requestPointerLock")}}, which is vendor-prefixed for now. You would currently declare it something like this, for example if you wanted to request pointer lock on a <code>canvas</code> element.:</p>

<pre class="brush: js">
canvas.requestPointerLock = canvas.requestPointerLock ||
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;                   canvas.mozRequestPointerLock;

canvas.requestPointerLock()
</pre>

<h3 id="pointerLockElement_and_exitPointerLock()">pointerLockElement and exitPointerLock()</h3>

<p>The Pointer lock API also extends the {{domxref("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 {{domxref("Document.pointerLockElement","pointerLockElement")}}, which is vendor-prefixed for now. The new method on {{domxref("Document")}} is {{domxref("Document.exitPointerLock","exitPointerLock")}} and, as the name implies, it is used to exit Pointer lock.</p>

<p>The {{domxref("Document.pointerLockElement","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.</p>

<p>Here is an example of using <code>pointerLockElement</code>:</p>

<pre class="brush: js">
<span class="idlInterface" id="idl-def-MouseLockable"><span class="idlInterface" id="idl-def-MouseLockable">if(document.pointerLockElement === canvas ||
&nbsp; document.mozPointerLockElement === canvas) {
&nbsp;&nbsp;&nbsp; console.log('The pointer lock status is now locked');
} else {
&nbsp;&nbsp;&nbsp; console.log('The pointer lock status is now unlocked'); &nbsp;
}</span></span></pre>

<p>The {{domxref("Document.exitPointerLock")}} method is used to exit pointer lock, and like {{domxref("Element.requestPointerLock","requestPointerLock")}}, works asynchronously using the {{event("pointerlockchange")}} and {{event("pointerlockerror")}} events, which you'll see more about below.</p>

<pre class="brush: js">
document.exitPointerLock = document.exitPointerLock    ||
                           document.mozExitPointerLock;

// Attempt to unlock
document.exitPointerLock();
</pre>

<h2 id="mouselocklostevent" name="mouselocklostevent">pointerlockchange event</h2>

<p>When the Pointer lock state changes—for example, when calling {{domxref("Element.requestPointerLock","requestPointerLock")}}, {{domxref("Document.exitPointerLock","exitPointerLock")}}, the user pressing the ESC key, etc.—the {{event("pointerlockchange")}} event is dispatched to the <code>document</code>. This is a simple event and contains no extra data.</p>

<pre class="brush: js">
if ("onpointerlockchange" in document) {
  document.addEventListener('pointerlockchange', lockChangeAlert, false);
} else if ("onmozpointerlockchange" in document) {
  document.addEventListener('mozpointerlockchange', lockChangeAlert, false);
}

function lockChangeAlert() {
&nbsp; if(document.pointerLockElement === canvas ||
&nbsp; document.mozPointerLockElement === canvas) {
&nbsp;&nbsp;&nbsp; console.log('The pointer lock status is now locked');
&nbsp;&nbsp;&nbsp; // Do something useful in response
  } else {
&nbsp;&nbsp;&nbsp; console.log('The pointer lock status is now unlocked'); &nbsp;&nbsp;&nbsp;&nbsp; 
    // Do something useful in response
  }
}</pre>

<h2 id="mouselocklostevent" name="mouselocklostevent">pointerlockerror event</h2>

<p>When there is an error caused by calling {{domxref("Element.requestPointerLock","requestPointerLock")}} or {{domxref("Document.exitPointerLock","exitPointerLock")}}, the {{event("pointerlockerror")}} event is dispatched to the <code>document</code>. This is a simple event and contains no extra data.</p>

<pre class="brush: js">
document.addEventListener('pointerlockerror', lockError, false);
document.addEventListener('mozpointerlock<span style="font-size:1rem">error</span><span style="font-size:1rem">', lockError, false);</span>

function lockError(e) {
  alert("Pointer lock failed"); 
}</pre>

<div class="note"><strong>Note</strong>: The above events are currently prefixed with <code>moz</code> in Firefox.&nbsp;</div>

<h2 id="extensions" name="extensions">Extensions to mouse events</h2>

<p>The&nbsp;Pointer lock API extends the normal {{domxref("MouseEvent")}} interface with movement attributes.</p>

<pre class="idl">
<span class="idlInterface" id="idl-def-MouseEvent">partial interface <span class="idlInterfaceID">MouseEvent</span> {
<span class="idlAttribute">    readonly attribute <span class="idlAttrType"><a>long</a></span> <span class="idlAttrName"><a href="https://dvcs.w3.org/hg/webevents/raw-file/default/mouse-lock.html#widl-MouseEvent-movementX">movementX</a></span>;</span>
<span class="idlAttribute">    readonly attribute <span class="idlAttrType"><a>long</a></span> <span class="idlAttrName"><a href="https://dvcs.w3.org/hg/webevents/raw-file/default/mouse-lock.html#widl-MouseEvent-movementY">movementY</a></span>;</span>
};</span></pre>

<div class="note">The movement attributes are currently prefixed as <code>.mozMovementX</code> and <code>.mozMovementY</code> in Firefox.</div>

<p>Two new parameters to mouse events—{{domxref("MouseEvent.movementX","movementX")}} and {{domxref("MouseEvent.movementY","movementY")}}—provide the change in mouse positions. The values of the parameters are the same as the difference between the values of {{domxref("MouseEvent")}} properties, {{domxref("MouseEvent.screenX","screenX")}} and {{domxref("MouseEvent.screenY","screenY")}}, which are stored in two subsequent {{event("mousemove")}} events,&nbsp;<code>eNow</code>&nbsp;and&nbsp;<code>ePrevious</code>. In other words, the Pointer lock parameter&nbsp;<code>movementX = eNow.screenX - ePrevious.screenX</code>.</p>

<h3 id="locked_state" name="locked_state">Locked state</h3>

<p>When Pointer&nbsp;lock is enabled, the standard {{domxref("MouseEvent")}} properties {{domxref("MouseEvent.clientX","clientX")}}, {{domxref("MouseEvent.clientY","clientY")}}, {{domxref("MouseEvent.screenX","screenX")}}, and {{domxref("MouseEvent.screenY","screenY")}} are held constant, as if the mouse is not moving. The {{domxref("MouseEvent.movementX","movementX")}} and {{domxref("MouseEvent.movementY","movementY")}} properties continue to provide the mouse's change in position. There is no limit to {{domxref("MouseEvent.movementX","movementX")}} and {{domxref("MouseEvent.movementY","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.</p>

<h3 id="unlocked_state" name="unlocked_state">Unlocked state</h3>

<p>The parameters {{domxref("MouseEvent.movementX","movementX")}} and {{domxref("MouseEvent.movementY","movementY")}} are valid regardless of the mouse&nbsp;lock state, and are available even when unlocked for convenience.</p>

<p>When the&nbsp;mouse&nbsp;is unlocked, the system cursor can exit and re-enter the browser window. If that happens, {{domxref("MouseEvent.movementX","movementX")}} and {{domxref("MouseEvent.movementY","movementY")}} could be set to zero.</p>

<h2 id="example" name="example">Simple example walkthrough</h2>

<p>We've written a <a href="https://mdn.github.io/pointer-lock-demo/">simple pointer lock demo</a> to show you how to use it to set up a simple control system (<a href="https://github.com/mdn/pointer-lock-demo">see source code</a>). The demo looks like this:</p>

<p><img alt="A red circle on top of a black background." src="https://mdn.mozillademos.org/files/7953/pointer-lock.png" style="display:block; height:362px; margin:0px auto; width:640px" /></p>

<p>This demo uses JavaScript to draw a ball on top of an {{ htmlelement("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.</p>

<p>Set initial x and y positions on the canvas:</p>

<pre class="brush: js">
var x = 50;
var y = 50;</pre>

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

<pre class="brush: js">
function canvasDraw() {
  if(x &gt; canvas.width+20) {
    x = 0;  
  }

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

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

  if(y &lt; -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();
}</pre>

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

<pre class="brush: js">
canvas.requestPointerLock = canvas.requestPointerLock ||
           canvas.mozRequestPointerLock;
// pointer lock object forking for cross browser

document.exitPointerLock = document.exitPointerLock ||
         document.mozExitPointerLock;
//document.exitPointerLock();</pre>

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

<pre class="brush: js">
canvas.onclick = function() {
  canvas.requestPointerLock();
}</pre>

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

<pre class="brush: js">
// pointer lock event listener

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

<p>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 <code>canvasLoop()</code> function. If not, it removes the event listener again.</p>

<pre class="brush: js">
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);
  }
}</pre>

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

<pre class="brush: js">
  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';</pre>

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

<pre>
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;
}</pre>

<h2 id="iframe_limitations">iframe limitations</h2>

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

<p>While iframes work by default, "sandboxed" iframes block Pointer lock. The ability to avoid this limitation, in the form of the attribute/value combination <code>&lt;iframe sandbox="allow-pointer-lock"&gt;</code>, is expected to appear in Chrome soon.</p>

<h2 id="Specifications">Specifications</h2>

<table class="standard-table">
 <thead>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>{{SpecName('Pointer Lock')}}</td>
   <td>{{Spec2('Pointer Lock')}}</td>
   <td>Initial specification.</td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility" name="Browser_compatibility">Browser compatibility</h2>

<p>{{ CompatibilityTable() }}</p>

<div id="compat-desktop">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Chrome</th>
   <th>Edge</th>
   <th>Firefox (Gecko)</th>
   <th>Internet Explorer</th>
   <th>Opera</th>
   <th>Safari (WebKit)</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>
    <p>Yes</p>
   </td>
   <td>Yes</td>
   <td>
    <p>Yes {{ property_prefix("gecko") }}</p>
   </td>
   <td>{{ CompatNo() }}</td>
   <td>Yes</td>
   <td>{{ CompatNo() }}</td>
  </tr>
 </tbody>
</table>
</div>

<div id="compat-mobile">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Android</th>
   <th>Firefox Mobile (Gecko)</th>
   <th>Firefox OS</th>
   <th>IE&nbsp;Phone</th>
   <th>Opera Mobile</th>
   <th>Safari Mobile</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{ CompatNo() }}</td>
   <td>{{ CompatNo() }}</td>
   <td>{{ CompatNo() }}</td>
   <td>{{ CompatNo() }}</td>
   <td>{{ CompatNo() }}</td>
   <td>{{ CompatNo() }}</td>
  </tr>
 </tbody>
</table>
</div>

<h2 id="See_also" name="See_also">See also</h2>

<ul>
 <li>{{domxref("MouseEvent")}}</li>
</ul>
Revert to this revision