aboutsummaryrefslogtreecommitdiff
path: root/files/es/webapi/pointer_lock/index.html
blob: 13a27d6d489ecdf9ea47e5d188651c3753f7de25 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
---
title: API Pointer Lock
slug: WebAPI/Pointer_Lock
translation_of: Web/API/Pointer_Lock_API
---
<p> </p>

<p><strong>Pointer Lock </strong>(antes llamado Bloqueo del <em>Mouse</em>)  proporciona métodos de entrada basados ​​en el movimiento del ratón a traves del tiempo (es decir, deltas), no sólo la posición absoluta del cursor del <em>mouse</em>. Te da acceso al movimiento <span style="line-height: inherit;">puro </span><span style="line-height: inherit;">del <em>mouse</em>, bloquea el objetivo de los eventos del <em>mouse</em> a un solo elemento, elimina límites en cuanto a  que tan lejos puedes mover el <em>mouse</em> en una sola dirección, y quita el cursor de la vista.</span></p>

<p>Esta API es útil para aplicaciones que requieren bastantes acciones para controlar los movimientos del <em>mouse</em>, rotar objetos y cambiar las entradas. Es especialmente importante para aplicaciones altamente visuales, tales como los que utilizan la perspectiva en primera persona, así como vistas en 3D y modelado.</p>

<p>Por ejemplo, puedes crear aplicaciones que permiten a los usuarios controlar el ángulo de visión con sólo mover el <em>mouse</em> sin ningún clic, permitiendo liberar <span style="line-height: inherit;">los clics</span><span style="line-height: inherit;"> para otras acciones. Este tipo de entrada del <em>mouse</em> es muy útil para ver mapas, imágenes de satélite, o escenas en primera persona (como en un juego o un vídeo embebido).</span></p>

<p><strong>Pointer Lock</strong><span style="line-height: inherit;"> te permite acceder a los eventos del </span><em>mouse</em><span style="line-height: inherit;"> incluso cuando el cursor pasa por el límite de la pantalla del navegador. Por ejemplo, los usuarios pueden seguir girando o manipular un modelo 3D moviendo el </span><em>mouse</em><span style="line-height: inherit;"> sin fin. Sin </span><strong>Pointer Lock</strong><span style="line-height: inherit;">, la rotación o la manipulación se detiene en el momento en que el cursor alcanza el borde de la pantalla del navegador. Los jugadores se verán particularmente encantados con esta característica, ya que anciosamente pueden hacer clic en los botones y arrastrar el cursor del </span><em>mouse</em><span style="line-height: inherit;"> de un lado a otro sin tener que preocuparse por salir de la zona de juego ni de cliquear accidentalmente otra aplicación que podría llevar al </span><em>mouse</em><span style="line-height: inherit;"> fuera del juego. Una tragedia!</span></p>

<h2 id="basics" name="basics">Conceptos Básicos</h2>

<p><strong>Pointer Lock</strong><strong style="line-height: inherit;"> </strong><span style="line-height: inherit;">está relacionado con la <em>mouse capture</em></span><em>mouse capture </em><span style="line-height: inherit;">proporciona la entrega continua de eventos a un elemento de destino, mientras que el <em>mouse</em> se arrastra, pero se detiene cuando se suelta el clic. </span><strong>Pointer Lock</strong><span style="line-height: inherit;"> es diferente de </span><em>mouse capture </em><span style="line-height: inherit;">en las siguientes maneras:</span></p>

<ul>
 <li><span style="line-height: 1.5em;">Es persistente. <strong style="line-height: normal;">Pointer Lock</strong> no libera el <em>mouse</em> hasta que se haga una llamada explícita a la API  o el usuario utilize un gesto concreto de lanzamiento.</span></li>
 <li><span style="line-height: 1.5em;">No está limitado por los limites del navegador o la pantalla.</span></li>
 <li>Envia continuamente eventos independientemente del estado del clic del <em>mouse</em>.</li>
 <li>Oculta el cursor.</li>
</ul>

<h2 id="example" name="example">Ejemplo</h2>

<p>El siguiente es un ejemplo de cómo se puede configurar <strong>Pointer Lock</strong> en su página web.</p>

<pre class="brush: js">&lt;button onclick="lockPointer();"&gt;Lock it!&lt;/button&gt;
&lt;div id="pointer-lock-element"&gt;&lt;/div&gt;
&lt;script&gt;
// Nota: Al momento de escribir esto, sólo Mozilla y WebKit apoyan Pointer Lock.

// El elemento que servirá para pantalla completa y pointer lock.
var elem;

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

  // Imprime los valores delta del movimiento del mouse
  console.log("movementX=" + movementX, "movementY=" + movementY);
}, false);

function fullscreenChange() {
  if (document.webkitFullscreenElement === elem ||
      document.mozFullscreenElement === elem ||
      document.mozFullScreenElement === elem) { // Older API upper case 'S'.
    // El elemento esta en pantalla completa, ahora podemos hacer el request de 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();
}
&lt;/script&gt;
</pre>

<h2 id="method_overview" name="method_overview">Propiedades/Métodos</h2>

<p>La API de bloque de puntero ,similar a la API de Fullscreen,extiende del elemento DOM agregando un nuevo método, <code>requestPointerLock</code>, la cual es dependiente del vendedor(del navegador). Puede escribirse como:</p>

<pre class="idl"><span class="idlInterface" id="idl-def-MouseLockable"><span class="idlInterface" id="idl-def-MouseLockable">element.webkitRequestPointerLock(); // para Chrome</span></span>

element.mozRequestPointerLock(); // para Firefox
</pre>

<p>Current implementations of <code>requestPointerLock</code> are tightly bound to <code>requestFullScreen</code> 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 (<code>pointerlockchange</code>, <code>pointerlockerror</code>) indicating the success or failure of the request. This matches how the Fullscreen API works, with its <code>requestFullScreen</code> method and <code>fullscreenchange</code> and <code>fullscreenerror</code> events.</p>

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

<p>The <code>pointerLockElement</code> 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:</p>

<pre class="idl"><span class="idlInterface" id="idl-def-MouseLockable"><span class="idlInterface" id="idl-def-MouseLockable">document.pointerLockElement = document.pointerLockElement    ||
                              document.mozPointerLockElement ||
                              document.webkitPointerLockElement;</span></span>

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

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

<pre class="idl"><span class="idlInterface" id="idl-def-MouseLockable"><span class="idlInterface" id="idl-def-MouseLockable">document.exitPointerLock = document.exitPointerLock    ||
                           document.mozExitPointerLock ||
                           document.webkitExitPointerLock;</span></span>

function pointerLockChange() {
  <span class="idlInterface" id="idl-def-MouseLockable"><span class="idlInterface" id="idl-def-MouseLockable">document.pointerLockElement = document.pointerLockElement    ||
                                document.mozPointerLockElement ||
                                document.webkitPointerLockElement;</span></span>

  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();
</pre>

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

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

<div class="note">This event is currently prefixed as <code>mozpointerlockchange</code> in Firefox and <code>webkitpointerlockchange</code> in Chrome. </div>

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

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

<div class="note">This event is currently prefixed as <code>mozpointerlockerror</code> in Firefox and <code>webkitpointerlockerror</code> in Chrome. </div>

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

<p>The Pointer lock API extends the normal <code>MouseEvent</code> 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="http://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="http://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, and<code>.webkitMovementX</code> and <code>.webkitMovementY</code> in Chrome.</div>

<p>Two new parameters to mouse events—<code>movementX</code> and <code>movementY</code>—provide the change in mouse positions. The values of the parameters are the same as the difference between the values of <a href="/en/DOM/MouseEvent" title="en/DOM/Event/UIEvent/MouseEvent"><code>MouseEvent</code></a> properties, <code>screenX</code> and <code>screenY</code>, which are stored in two subsequent <code>mousemove</code> events, <code>eNow</code> and <code>ePrevious</code>. In other words, the Pointer lock parameter <code>movementX = eNow.screenX - ePrevious.screenX</code>.</p>

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

<p>When Pointer lock is enabled, the standard <code>MouseEvent</code> properties <code>clientX</code>, <code>clientY</code>, <code>screenX</code>, and <code>screenY</code> are held constant, as if the mouse is not moving. The <code>movementX</code> and <code>movementY</code> properties continue to provide the mouse's change in position. There is no limit to <code>movementX</code> and <code>movementY</code> 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 <code>movementX</code> and <code>movementY</code> are valid regardless of the mouse lock state, and are available even when unlocked for convenience.</p>

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

<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>Firefox (Gecko)</th>
   <th>Internet Explorer</th>
   <th>Opera</th>
   <th>Safari (WebKit)</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>
    <p>Targeting 23{{ property_prefix("webkit") }}*</p>

    <p>See <a class="external" href="http://code.google.com/p/chromium/issues/detail?id=72754" title="http://code.google.com/p/chromium/issues/detail?id=72754">CR/72574</a></p>
   </td>
   <td>
    <p>{{ CompatGeckoDesktop("14.0") }}</p>

    <p>{{bug("633602") }}</p>
   </td>
   <td>{{ CompatNo() }}</td>
   <td>{{ CompatNo() }}</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>IE 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>
  </tr>
 </tbody>
</table>
</div>

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

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

<p><a href="/en/DOM/MouseEvent" title="en/DOM/Event/UIEvent/MouseEvent">MouseEvent</a></p>