Gamepad Input
Many players prefer a controller, and browsers support Xbox, PlayStation and most other USB or Bluetooth gamepads through the Gamepad API. It works differently from the keyboard: there are no events for buttons or sticks. Instead, your game polls the current state once per update.
Polling the pads
function readPad() {
const pads = navigator.getGamepads(); // an array with null for empty slots
for (const pad of pads) {
if (pad && pad.connected) return pad; // use the first connected pad
}
return null;
}A gamepad object has:
| Property | Contents |
|---|---|
pad.buttons[i].pressed / .value |
Each button: pressed (true/false) and how far (0–1, for analogue triggers) |
pad.axes[i] |
Sticks, from −1 to 1: axes[0]/axes[1] = left stick x/y, axes[2]/axes[3] = right stick |
pad.mapping |
"standard" when the browser could map the pad to the standard layout below |
pad.id |
A description such as "Xbox Wireless Controller (STANDARD GAMEPAD …)" |
With mapping === "standard", the button indices are the same on every pad:
| Index | Button | Index | Button |
|---|---|---|---|
| 0 | A / Cross (bottom) | 8 | Back / Select / Share |
| 1 | B / Circle (right) | 9 | Start / Options |
| 2 | X / Square (left) | 12, 13 | D-pad up, down |
| 3 | Y / Triangle (top) | 14, 15 | D-pad left, right |
| 4, 5 | LB, RB (bumpers) | 6, 7 | LT, RT (analogue triggers) |
Note: Browsers hide gamepads until the player presses a button on one while the page is open, so a pad can't be used to fingerprint visitors. Show a hint such as "Press any button on your controller". Inside an embedded frame, a site can also block the API with a permissions policy, so wrap the call in
try/catchand fall back to the keyboard.
Dead zones
Sticks rarely rest at exactly 0; a worn stick may report 0.08 while untouched, and the character drifts. A dead zone ignores small values. Treating x and y separately (an "axial" dead zone) makes diagonal movement stick to the axes, so games use a radial dead zone on the stick's length, then rescale so movement still starts smoothly from 0:
function radialDeadZone(x, y, dead = 0.2) {
const len = Math.hypot(x, y);
if (len < dead) return [0, 0];
const scaled = Math.min(1, (len - dead) / (1 - dead)); // dead..1 becomes 0..1
return [+(x / len * scaled).toFixed(3), +(y / len * scaled).toFixed(3)];
}
for (const [x, y] of [[0.08, -0.05], [0.25, 0], [0.6, 0], [0.5, 0.5], [1, 0], [0.9, 0.9]]) {
console.log(`(${x}, ${y}) ->`, radialDeadZone(x, y));
}(0.08, -0.05) -> [ 0, 0 ]
(0.25, 0) -> [ 0.062, 0 ]
(0.6, 0) -> [ 0.5, 0 ]
(0.5, 0.5) -> [ 0.448, 0.448 ]
(1, 0) -> [ 1, 0 ]
(0.9, 0.9) -> [ 0.707, 0.707 ]
The resting stick gives exactly 0, a small push gives a small value (not a sudden jump to 0.2), and a full diagonal push is clamped to length 1.
Pressed this update
Buttons have no keydown event, so "pressed since the last update" is computed by comparing with the previous poll:
let prevButtons = [];
function padPressed(pad, index) {
return pad.buttons[index].pressed && !prevButtons[index];
}
// at the end of update():
prevButtons = pad ? pad.buttons.map((b) => b.pressed) : [];One set of actions for every device
Combine keyboard and gamepad into the same actions, as in the keyboard lesson. The game logic then never knows which device the player uses. Connect a controller, press a button, and drive with the left stick or D-pad; A jumps (the circle grows), B changes color. The keyboard (arrows + Space) works too.
<style>
html, body { margin: 0; height: 100%; background: #0e1018; overflow: hidden; }
canvas { display: block; margin: 0 auto; width: min(100vw, 177.78vh); height: auto; outline: none; touch-action: none; }
</style>
<canvas width="480" height="270"></canvas>
<script>
// ---- play kit: click to focus, keep game keys inside the frame, fixed-step loop ----
const cv = document.querySelector('canvas'), ctx = cv.getContext('2d');
const W = cv.width, H = cv.height;
const keys = new Set(), pressed = new Set(); // keys held now / pressed since the last update
let active = false, idleDrawn = false;
cv.tabIndex = 0;
cv.addEventListener('pointerdown', () => cv.focus());
cv.addEventListener('focus', () => { active = true; });
cv.addEventListener('blur', () => { active = false; idleDrawn = false; keys.clear(); pressed.clear(); });
addEventListener('keydown', (e) => {
if (e.code.startsWith('Arrow') || e.code === 'Space') e.preventDefault(); // don't scroll the lesson
if (!e.repeat) pressed.add(e.code);
keys.add(e.code);
});
addEventListener('keyup', (e) => keys.delete(e.code));
function banner(title, sub = '') {
ctx.save();
ctx.fillStyle = 'rgba(0,0,0,0.6)'; ctx.fillRect(0, 0, W, H);
ctx.fillStyle = '#fff'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.font = 'bold 22px system-ui, sans-serif'; ctx.fillText(title, W / 2, H / 2 - 10);
ctx.font = '14px system-ui, sans-serif'; ctx.fillText(sub, W / 2, H / 2 + 18);
ctx.restore();
}
function run(update, draw, help = '') {
const STEP = 1 / 60;
let acc = 0, last = performance.now();
requestAnimationFrame(function frame(now) {
const dt = Math.min((now - last) / 1000, 0.1);
last = now;
if (active) {
acc += dt;
while (acc >= STEP) { update(STEP); pressed.clear(); acc -= STEP; }
draw();
} else if (!idleDrawn) {
draw(); banner('Click to play', help); idleDrawn = true;
}
requestAnimationFrame(frame);
});
}
// ---- end of play kit ----
let padStatus = 'Press a button on a controller';
let prevButtons = [];
function readPad() {
try {
for (const pad of navigator.getGamepads()) if (pad && pad.connected) return pad;
} catch (err) {
padStatus = 'Gamepads blocked here: ' + err.name; // keyboard still works
}
return null;
}
function radialDeadZone(x, y, dead = 0.2) {
const len = Math.hypot(x, y);
if (len < dead) return [0, 0];
const s = Math.min(1, (len - dead) / (1 - dead));
return [x / len * s, y / len * s];
}
const dot = { x: 240, y: 135, jump: 0, hue: 200 };
function update(dt) {
const pad = readPad();
const btn = (i) => !!pad && !!pad.buttons[i] && pad.buttons[i].pressed;
const padPressed = (i) => btn(i) && !prevButtons[i];
// keyboard part of each action
let mx = (keys.has('ArrowRight') || keys.has('KeyD') ? 1 : 0) - (keys.has('ArrowLeft') || keys.has('KeyA') ? 1 : 0);
let my = (keys.has('ArrowDown') || keys.has('KeyS') ? 1 : 0) - (keys.has('ArrowUp') || keys.has('KeyW') ? 1 : 0);
let jump = pressed.has('Space');
let recolor = pressed.has('KeyC');
// gamepad part of each action
if (pad) {
padStatus = pad.id.slice(0, 48);
const [sx, sy] = radialDeadZone(pad.axes[0] ?? 0, pad.axes[1] ?? 0);
mx += sx + (btn(15) ? 1 : 0) - (btn(14) ? 1 : 0);
my += sy + (btn(13) ? 1 : 0) - (btn(12) ? 1 : 0);
jump ||= padPressed(0);
recolor ||= padPressed(1);
prevButtons = pad.buttons.map((b) => b.pressed);
}
const len = Math.hypot(mx, my);
if (len > 1) { mx /= len; my /= len; } // never faster than full speed
dot.x = Math.max(20, Math.min(W - 20, dot.x + mx * 180 * dt));
dot.y = Math.max(40, Math.min(H - 20, dot.y + my * 180 * dt));
if (jump) dot.jump = 0.3;
if (recolor) dot.hue = (dot.hue + 70) % 360;
dot.jump = Math.max(0, dot.jump - dt);
}
function draw() {
ctx.fillStyle = '#1a1a2e'; ctx.fillRect(0, 0, W, H);
const r = 14 + Math.sin((dot.jump / 0.3) * Math.PI) * 10;
ctx.fillStyle = `hsl(${dot.hue}, 80%, 60%)`;
ctx.beginPath(); ctx.arc(Math.round(dot.x), Math.round(dot.y), r, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = '#fff'; ctx.font = '13px system-ui, sans-serif'; ctx.textAlign = 'left';
ctx.fillText('Gamepad: ' + padStatus, 10, 20);
ctx.fillText('Stick/D-pad or arrows move · A or Space jumps · B or C recolors', 10, 260);
}
run(update, draw, 'Arrows + Space, or a gamepad (press a button first)');
</script>Vibration
Many pads can rumble. Chrome and Edge expose it as pad.vibrationActuator.playEffect('dual-rumble', { duration: 120, strongMagnitude: 0.6, weakMagnitude: 0.3 }); support varies between browsers and pads, so check that pad.vibrationActuator exists and treat rumble as a bonus, never as the only feedback.
Test yourself
How does a game learn the current state of a gamepad's buttons?
- From
buttondownevents - By polling
navigator.getGamepads()every update - From
keydownevents with special codes - By calling
pad.listen()once
Why use a dead zone on analogue sticks?
- To make sticks faster
- A stick at rest rarely reports exactly 0, and without a dead zone the character drifts
- Because axes go from 0 to 255
- To support vibration
With the standard mapping, which button index is the bottom face button (A on Xbox, Cross on PlayStation)?
- 0
- 1
- 9
- 12