canvas.addEventListener("click", async () => {
await canvas.requestPointerLock();
});Pointer Lock API / notebook
Pointer Lock API
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
canvas.addEventListener("click", async () => {
await canvas.requestPointerLock({
unadjustedMovement: true,
});
});function requestPointerLockWithUnadjustedMovement() {
const promise = myTargetElement.requestPointerLock({
unadjustedMovement: true,
});
if (!promise) {
console.log("disabling mouse acceleration is not supported");
return;
}
return promise
.then(() => console.log("pointer is locked"))
.catch((error) => {
if (error.name === "NotSupportedError") {
// Some platforms may not support unadjusted movement.
// You can request again a regular pointer lock.
return myTargetElement.requestPointerLock();
}
});
}if (document.pointerLockElement === canvas) {
console.log("The pointer lock status is now locked");
} else {
console.log("The pointer lock status is now unlocked");
}document.exitPointerLock();document.addEventListener("pointerlockchange", lockChangeAlert);
function lockChangeAlert() {
if (document.pointerLockElement === 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
}
}document.addEventListener("pointerlockerror", lockError);
function lockError(e) {
alert("Pointer lock failed");
}let x = 50;
let y = 50;canvas.addEventListener("click", async () => {
if (!document.pointerLockElement) {
await canvas.requestPointerLock({
unadjustedMovement: true,
});
}
});document.addEventListener("pointerlockchange", lockChangeAlert);function lockChangeAlert() {
if (document.pointerLockElement === canvas) {
console.log("The pointer lock status is now locked");
document.addEventListener("mousemove", updatePosition);
} else {
console.log("The pointer lock status is now unlocked");
document.removeEventListener("mousemove", updatePosition);
}
}const tracker = document.getElementById("tracker");
let animation;
function updatePosition(e) {
x += e.movementX;
y += e.movementY;
if (x > canvas.width + RADIUS) {
x = -RADIUS;
}
if (y > canvas.height + RADIUS) {
y = -RADIUS;
}
if (x < -RADIUS) {
x = canvas.width + RADIUS;
}
if (y < -RADIUS) {
y = canvas.height + RADIUS;
}
tracker.textContent = `X position: ${x}, Y position: ${y}`;
animation ??= requestAnimationFrame(() => {
animation = null;
canvasDraw();
});
}function canvasDraw() {
ctx.fillStyle = "black";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "red";
ctx.beginPath();
ctx.arc(x, y, RADIUS, 0, degToRad(360), true);
ctx.fill();
}