Mouse & Touch Input
Mouse and touch let players aim, drag and tap. Browsers report all of them through one family of pointer events (pointerdown, pointermove, pointerup), so one set of handlers covers a mouse, a finger and a pen. The work is in converting a position on the screen into a position in your game.
From screen pixels to game coordinates
Pointer events give clientX / clientY in CSS pixels relative to the frame's viewport. The canvas is somewhere in that viewport and scaled (your 480 × 270 game may be displayed 834 pixels wide, or 375). getBoundingClientRect() tells you where and how big the canvas is on screen; the rest is a proportion:
function toGame(e) {
const r = canvas.getBoundingClientRect();
return {
x: (e.clientX - r.left) * (canvas.width / r.width),
y: (e.clientY - r.top) * (canvas.height / r.height),
};
}The same calculation without a browser, for three display sizes:
function toGame(clientX, clientY, rect, gameW = 480, gameH = 270) {
return {
x: Math.round((clientX - rect.left) * (gameW / rect.width)),
y: Math.round((clientY - rect.top) * (gameH / rect.height)),
};
}
const shown1x = { left: 0, top: 0, width: 480, height: 270 };
const lessonFrame = { left: 168, top: 0, width: 498, height: 280 };
const phone = { left: 0, top: 34, width: 375, height: 211 };
console.log(toGame(240, 135, shown1x)); // centre at 1:1
console.log(toGame(417, 140, lessonFrame)); // centre of the lesson frame
console.log(toGame(187.5, 139.5, phone)); // centre on a phone
console.log(toGame(10, 10, lessonFrame)); // left of the canvas: negative x{ x: 240, y: 135 }
{ x: 240, y: 135 }
{ x: 240, y: 135 }
{ x: -152, y: 10 }
The last line is a reminder: a pointer outside the canvas maps to coordinates outside the game. Clamp them or ignore them.
Pointer events for games
| Event / property | Use |
|---|---|
pointerdown, pointermove, pointerup |
Press, move, release, for mouse, touch and pen alike |
pointercancel |
The browser took the touch away (for example a system gesture); treat it as pointerup |
e.pointerId |
Tells fingers apart in multi-touch |
e.pointerType |
"mouse", "touch" or "pen", if you need to behave differently |
e.button |
0 = left / touch, 2 = right (also block the contextmenu event to use right-click) |
canvas.setPointerCapture(e.pointerId) |
Keep receiving pointermove for this pointer even when it leaves the canvas (dragging) |
On touch screens the browser also wants to scroll and zoom when a finger moves. The CSS touch-action: none on the canvas turns that off for the canvas only, so the rest of the lesson still scrolls normally. The play kit's style rule already sets it.
Aim and shoot
Move the mouse (or drag a finger) to aim the turret; click, tap or hold to fire. Math.atan2(dy, dx) turns the vector from the turret to the pointer into an angle, which ctx.rotate uses directly.
<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 ----
const pointer = { x: 400, y: 80, down: false, type: 'mouse' };
function toGame(e) {
const r = cv.getBoundingClientRect();
pointer.x = (e.clientX - r.left) * (W / r.width);
pointer.y = (e.clientY - r.top) * (H / r.height);
pointer.type = e.pointerType;
}
cv.addEventListener('pointerdown', (e) => { toGame(e); pointer.down = true; cv.setPointerCapture(e.pointerId); });
cv.addEventListener('pointermove', toGame);
cv.addEventListener('pointerup', () => { pointer.down = false; });
cv.addEventListener('pointercancel', () => { pointer.down = false; });
cv.addEventListener('contextmenu', (e) => e.preventDefault());
const turret = { x: 70, y: 200, angle: 0, cooldown: 0 };
const shots = [];
let fired = 0;
function update(dt) {
turret.angle = Math.atan2(pointer.y - turret.y, pointer.x - turret.x);
turret.cooldown -= dt;
if ((pointer.down || keys.has('Space') || pressed.has('Space')) && turret.cooldown <= 0) {
turret.cooldown = 0.12; // max ~8 shots per second
shots.push({ x: turret.x + Math.cos(turret.angle) * 26, y: turret.y + Math.sin(turret.angle) * 26,
vx: Math.cos(turret.angle) * 420, vy: Math.sin(turret.angle) * 420, life: 1.2 });
fired++;
}
for (const s of shots) { s.x += s.vx * dt; s.y += s.vy * dt; s.life -= dt; }
for (let i = shots.length - 1; i >= 0; i--) if (shots[i].life <= 0) shots.splice(i, 1);
}
function draw() {
ctx.fillStyle = '#102027'; ctx.fillRect(0, 0, W, H);
ctx.fillStyle = '#ffee58';
for (const s of shots) ctx.fillRect(Math.round(s.x) - 2, Math.round(s.y) - 2, 4, 4);
ctx.save();
ctx.translate(turret.x, turret.y);
ctx.rotate(turret.angle);
ctx.fillStyle = '#90a4ae'; ctx.fillRect(0, -5, 28, 10); // barrel along +x
ctx.restore();
ctx.fillStyle = '#607d8b';
ctx.beginPath(); ctx.arc(turret.x, turret.y, 16, 0, Math.PI * 2); ctx.fill();
// crosshair at the pointer
ctx.strokeStyle = '#ef5350'; ctx.lineWidth = 2;
ctx.beginPath(); ctx.arc(Math.round(pointer.x), Math.round(pointer.y), 8, 0, Math.PI * 2); ctx.stroke();
ctx.fillStyle = '#fff'; ctx.font = '13px system-ui, sans-serif'; ctx.textAlign = 'left';
ctx.fillText(`pointer ${Math.round(pointer.x)}, ${Math.round(pointer.y)} (${pointer.type}) angle ${(turret.angle * 180 / Math.PI).toFixed(0)}° shots ${fired}`, 10, 20);
}
run(update, draw, 'Aim with the mouse or a finger; click, tap or Space to fire');
</script>Touch controls
A phone has no keyboard, so action games draw virtual controls: a joystick on the left half of the screen and buttons on the right. Multi-touch works by tracking each pointerId separately:
const touches = new Map(); // pointerId -> { startX, startY, x, y }
canvas.addEventListener('pointerdown', (e) => {
const p = toGame(e);
touches.set(e.pointerId, { startX: p.x, startY: p.y, x: p.x, y: p.y });
canvas.setPointerCapture(e.pointerId);
});
canvas.addEventListener('pointermove', (e) => {
const t = touches.get(e.pointerId);
if (t) Object.assign(t, toGame(e));
});
canvas.addEventListener('pointerup', (e) => touches.delete(e.pointerId));
// In update(): a touch that started on the left half is the joystick
for (const t of touches.values()) {
if (t.startX < W / 2) {
const dx = t.x - t.startX, dy = t.y - t.startY;
const len = Math.hypot(dx, dy);
if (len > 6) { moveX = dx / len; moveY = dy / len; } // a small dead zone
}
}Tip: Make touch buttons big (at least about 48 CSS pixels) and put them where thumbs rest, near the bottom corners. Fingers hide what they touch, so give feedback around the finger, not under it.
Test yourself
The canvas buffer is 480 wide but is displayed 960 CSS pixels wide, starting at rect.left = 0. A click has clientX = 300. What is the game x?
- 300
- 600
- 150
- 480
What does touch-action: none on the canvas do?
- Disables touch input completely
- Stops the browser from scrolling or zooming when a finger moves on the canvas, so the game gets the moves
- Makes the canvas ignore the mouse
- Turns on multi-touch
Which call gives the angle from the turret to the pointer?
Math.atan(dy / dx)Math.atan2(dy, dx)with dx, dy = pointer − turretMath.hypot(dx, dy)Math.sin(dy) / Math.cos(dx)