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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
|
---
title: Pointer Lock API
slug: Web/API/Pointer_Lock_API
translation_of: Web/API/Pointer_Lock_API
---
<p><span class="seoSummary"><strong>Pointer lock</strong> <strong>API</strong>(прежнее название Mouse Lock API) </span><span style="line-height: 1.5;">обеспечивает методы ввода, основанные на движении мыши , а не только абсолютно позиционированых координатах курсора </span><span style="line-height: 1.5;">в окне. Это дает вам доступ к необработанным движениям мыши, прикрепляет курсор мыши к любому элементу </span><span style="line-height: 1.5;">в окне браузера</span><span style="line-height: 1.5;">, предоставляет возможность вычислять координаты мыши не ограниченной областью окна проекции, и скрывает курсор из поля зрения. Это идеальное решение для 3D игр, например.</span></p>
<p>Более того, API полезно для любых приложений, которые используют данные мыши для управления движениями, вращения обьектов и изменения записей. Например пользователь может управлять наклоном просто двигая мышь, не нажимая ни на какие кнопки. Сами кнопки освобождаются под другие задачи. Примерами могут послужить программы для просмотра карт или спутниковой съемки.</p>
<p>Блокировка указателя позволяет вам получить доступ к данным мыши, даже если курсор ушел за границы экрана или браузера. Например, ваши пользователи могут продолжать вращать или управлять 3D моделью движением мыши бесконечно. Без блокировки вращение или управление останавливается, как только курсор достигает края браузера или экрана. Геймеры теперь могут нажимать кнопки и водить курсором взад и вперед, не боясь покинуть игровое поле и случайно переключится на другое приложение.</p>
<h2 id="basics" name="basics">Основные концепции</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">Обзор методов/свойств</h2>
<p>Этот раздел содержит краткое описание каждого свойства и метода, связанного со спецификацией блокировки указателя.</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 ||
canvas.mozRequestPointerLock ||
canvas.webkitRequestPointerLock;
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 ||
document.mozPointerLockElement === canvas ||
document.webkitPointerLockElement === canvas) {
console.log('The pointer lock status is now locked');
} else {
console.log('The pointer lock status is now unlocked');
}</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 ||
document.webkitExitPointerLock;
// 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);
} else if ("onwebkitpointerlockchange" in document) {
document.addEventListener('webkitpointerlockchange', lockChangeAlert, false);
}
function lockChangeAlert() {
if(document.pointerLockElement === canvas ||
document.mozPointerLockElement === canvas ||
document.webkitPointerLockElement === 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
}
}</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>
document.addEventListener('webkitpointerlock<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 and <code>webkit</code> in Chrome. </div>
<h2 id="extensions" name="extensions">Extensions to mouse events</h2>
<p>The 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="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—{{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, <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 {{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 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, {{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="http://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 > canvas.clientWidth+20) {
x = 0;
}
if(y > canvas.clientHeight+20) {
y = 0;
}
if(x < -20) {
x = canvas.clientWidth;
}
if(y < -20) {
y = canvas.clientHeight;
}
ctx.fillStyle = "black";
ctx.fillRect(0,0,canvas.clientWidth,canvas.clientHeight);
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 ||
canvas.webkitRequestPointerLock;
// pointer lock object forking for cross browser
document.exitPointerLock = document.exitPointerLock ||
document.mozExitPointerLock ||
document.webkitExitPointerLock;
//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);
document.addEventListener('webkitpointerlockchange', 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 ||
document.webkitPointerLockElement === 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 ||
e.webkitMovementX ||
0;
var movementY = e.movementY ||
e.mozMovementY ||
e.webkitMovementY ||
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><iframe sandbox="allow-pointer-lock"></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>Yes {{ property_prefix("webkit") }}</p>
</td>
<td>
<p>Yes {{ property_prefix("gecko") }}</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>Firefox OS</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>
<td>{{ CompatNo() }}</td>
</tr>
</tbody>
</table>
</div>
<h2 id="See_also" name="See_also">See also</h2>
<ul>
<li>{{domxref("MouseEvent")}}</li>
</ul>
|