The Pointer Lock API (formerly called Mouse Lock API) provides input methods based on the movement of the mouse (i.e., deltas), not just the absolute position of the mouse cursor in the viewport. For more information, check out this link: developer.mozilla.org
This API gives unlimited access to the mouse inputs, coordinates, actions, and movement without restriction.
It is ideal for playing games, modeling a 3D model, etc.
requestPointerLock
: This method removes the mouse from the browser and sends events of the mouse state. This will persist until exitPointerLock
is called.
exitPointerLock
: This API releases the mouse pointer lock and restores the mouse cursor.
Let’s see an example:
<body>
<header>
<h2>Web APIs<h2>
</header>
<div>
<div>
<div>
Demo - PointerLock
</div>
<div>
<div id="error"></div>
<div id="box">
<div id="ball"></div>
</div>
</div>
</div>
</div>
</body>
<script>
const l = console.log
box.addEventListener("click", () => {
if(box.requestPointerLock)
box.requestPointerLock()
else {
error.innerHTML = "PointerLock API not supported in this device."
error.classList.remove("close")
}
})
document.addEventListener("pointerlockchange",(e)=> {
document.addEventListener("mousemove",(e)=> {
const {movementX, movementY} = e
ball.style.top=movementX + "px"
ball.style.left=movementY + "px"
})
})
</script>
We have a div#box
, and inside it, a div#ball
.
We set up a click event on the div#box
. When we click, it calls the requestPointerLock()
. This will make the cursor disappear.
PointerLock
has a pointerlockchange
event listener. This event is emitted when the pointer locks state changes.
Inside its callback, we attach it to the mousemov
event.
Its callback will be fired when the mouse is moved on the current browser tab.
In this callback, the current mouse position is sent to the argument.
We use it to get the current X and Y position of the mouse.
We set the top and left style property of the div#ball
with this information. So when we move our mouse around, we see a dancing ball.
Try it here: An API to simulate an FPS gaming experience in your browser. Pointer Lock API
Free Resources