Gamepad API
The Gamepad API allows web applications to respond to input from gamepads and other game controllers. It provides a standard way to access controller data (buttons, axes) across different browsers and operating systems.
1. Connecting and Disconnecting
The API provides events to detect when a gamepad is connected or disconnected.
window.addEventListener("gamepadconnected", (e) => {
console.log(
"Gamepad connected at index %d: %s. %d buttons, %d axes.",
e.gamepad.index,
e.gamepad.id,
e.gamepad.buttons.length,
e.gamepad.axes.length,
);
});
window.addEventListener("gamepaddisconnected", (e) => {
console.log(
"Gamepad disconnected from index %d: %s",
e.gamepad.index,
e.gamepad.id,
);
});
2. Accessing Gamepad State
Unlike keyboard or mouse events which fire when an action happens, the Gamepad API requires you to poll the state of the gamepad in a loop (usually using requestAnimationFrame).
You access the current state using navigator.getGamepads().
function gameLoop() {
const gamepads = navigator.getGamepads();
// gamepads is an array-like object. It may contain nulls.
if (gamepads[0]) {
const gp = gamepads[0];
// Check button 0 (usually 'A' or 'X')
if (gp.buttons[0].pressed) {
console.log("Button 0 pressed");
}
// Check axes (joysticks)
// axes[0] is usually Left Stick X-axis (-1.0 to 1.0)
// axes[1] is usually Left Stick Y-axis (-1.0 to 1.0)
const x = gp.axes[0];
const y = gp.axes[1];
// Apply a deadzone to avoid drift
if (Math.abs(x) > 0.1) {
console.log(`Moving X: ${x}`);
}
}
requestAnimationFrame(gameLoop);
}
gameLoop();
3. The Gamepad Object
A Gamepad object contains several key properties:
index: An integer that is unique for each gamepad currently connected to the system.id: A string containing some information about the controller (e.g., "Xbox 360 Controller").buttons: An array ofGamepadButtonobjects. Each button has apressed(boolean) andvalue(float 0.0-1.0, for triggers) property.axes: An array of floating point values representing the position of analog sticks.
4. Haptic Feedback (Vibration)
The GamepadHapticActuator interface allows you to vibrate the controller (if supported).
const gp = navigator.getGamepads()[0];
if (gp && gp.vibrationActuator) {
gp.vibrationActuator.playEffect("dual-rumble", {
startDelay: 0,
duration: 200,
weakMagnitude: 1.0,
strongMagnitude: 1.0,
});
}
5. Standard Mapping
Different controllers have different layouts. The API attempts to map them to a "Standard Gamepad" layout (similar to an Xbox 360 controller) if mapping is set to "standard".
buttons[0]: Bottom button in right cluster (A/Cross).buttons[1]: Right button in right cluster (B/Circle).axes[0]: Left stick horizontal.axes[1]: Left stick vertical.
programming/javascript/vanilla/javascript programming/javascript/vanilla/events programming/javascript/vanilla/canvas-api