Reputation: 1644
I want to completely disable the cursor in the browser, similarly to http://a-way-to-go.com/ and http://voxeljs.com/
When you open these projects, the cursor is disabled completely. No cursor, inside or outside of the browser. I'd like to know how to do this.
I'm not interested in cursor: none;
Upvotes: 3
Views: 4660
Reputation: 816364
They seems to be using the Pointer Lock API. From MDN:
Pointer lock (formerly called mouse lock) 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.
Detailed information about how to use it, especially cross-browser concerns, can be found on that page, but in short (snippets all copied from MDN):
Request pointer lock:
canvas.onclick = function() {
canvas.requestPointerLock();
}
document.addEventListener('pointerlockchange', lockChangeAlert, false);
React to pointer lock status change:
function lockChangeAlert() {
if(document.pointerLockElement === 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);
}
}
Example function that handles mouse move events:
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;
var animation = requestAnimationFrame(canvasLoop);
tracker.innerHTML = "X position: " + x + ', Y position: ' + y;
}
Upvotes: 6