HUD & Menus
The HUD (heads-up display) is everything drawn on top of the game world that tells the player how they are doing: score, health, lives, ammo, a timer. Menus are the screens around the game: title, options, pause, game over. Both are plain canvas drawing, but they follow a few rules that keep them readable while everything else is moving.
Rules for a readable HUD
| Rule | Why |
|---|---|
| Draw the HUD last, in screen space | It must sit on top of the world and ignore the camera and screen shake |
| Keep a safe margin (8–16 px) from the edges | Text glued to the border is hard to read, and TVs and rounded phone screens cut corners |
Set textAlign and textBaseline every time |
They are global context state; another function may have changed them |
| Use whole-pixel font sizes and positions | Fractional sizes and positions blur text, especially when the canvas is scaled up |
| Pad changing numbers | 000450 or a monospace font stops the text from jumping as digits change |
| Put a dark shadow or panel behind text | White text vanishes over a bright background |
| Show change, not just state | Flash the health bar, pop the score, use a trailing "damage" bar |
HUD helpers
Formatting logic is pure JavaScript, so it is easy to test without drawing anything:
const padScore = (n, width = 6) => String(n).padStart(width, '0');
const clock = (seconds) => `${Math.floor(seconds / 60)}:${String(Math.floor(seconds % 60)).padStart(2, '0')}`;
const barWidth = (hp, max, width) => Math.round(width * Math.max(0, Math.min(1, hp / max)));
// Hearts with halves: hp counts half-hearts, so 5 = two and a half hearts
function hearts(hp, maxHearts) {
let s = '';
for (let i = 0; i < maxHearts; i++) {
const left = hp - i * 2;
s += left >= 2 ? '♥' : left === 1 ? '½' : '·';
}
return s;
}
console.log(padScore(450), padScore(1234567));
console.log(clock(0), clock(75.9), clock(600));
console.log(barWidth(30, 100, 120), barWidth(-5, 100, 120), barWidth(150, 100, 120));
console.log(hearts(6, 3), hearts(5, 3), hearts(1, 3), hearts(0, 3));000450 1234567
0:00 1:15 10:00
36 0 120
♥♥♥ ♥♥½ ½·· ···
Note how barWidth clamps the ratio to 0..1: health that briefly drops below zero or a heal above the maximum must never draw a bar outside its frame. The second example shows that padStart never cuts a number that is already longer than the width.
A game with a HUD
Collect the yellow coins with the arrow keys and avoid the red drone. The HUD shows a padded score, a timer, a health bar with a trailing "damage" bar, and a "+10" pop-up that floats up where you grabbed the coin. When health reaches zero, press Enter to restart.
<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 SPOTS = [[60, 60], [420, 70], [240, 220], [90, 210], [380, 200], [240, 90], [150, 140], [330, 130]];
let player, drone, coin, score, time, hp, ghostHp, hurt, popups, spot, over;
function reset() {
player = { x: 240, y: 150, s: 14 };
drone = { x: 100, y: 100, vx: 110, vy: 80, r: 10 };
spot = 0; coin = SPOTS[0];
score = 0; time = 0; hp = 100; ghostHp = 100; hurt = 0; popups = []; over = false;
}
reset();
function update(dt) {
if (over) { if (pressed.has('Enter')) reset(); return; }
time += dt;
const sp = 150 * dt;
if (keys.has('ArrowLeft')) player.x -= sp;
if (keys.has('ArrowRight')) player.x += sp;
if (keys.has('ArrowUp')) player.y -= sp;
if (keys.has('ArrowDown')) player.y += sp;
player.x = Math.max(0, Math.min(W - player.s, player.x));
player.y = Math.max(40, Math.min(H - player.s, player.y)); // the top 40 px belong to the HUD
drone.x += drone.vx * dt; drone.y += drone.vy * dt;
if (drone.x < drone.r || drone.x > W - drone.r) drone.vx = -drone.vx;
if (drone.y < 40 + drone.r || drone.y > H - drone.r) drone.vy = -drone.vy;
const cx = player.x + player.s / 2, cy = player.y + player.s / 2;
if (Math.hypot(cx - coin[0], cy - coin[1]) < 16) {
score += 10;
popups.push({ x: coin[0], y: coin[1], t: 0 });
spot = (spot + 1) % SPOTS.length;
coin = SPOTS[spot];
}
if (hurt > 0) hurt -= dt;
else if (Math.hypot(cx - drone.x, cy - drone.y) < drone.r + 7) { hp -= 25; hurt = 0.8; }
ghostHp += (hp - ghostHp) * (1 - Math.exp(-3 * dt)); // trailing bar catches up smoothly
for (const p of popups) p.t += dt;
popups = popups.filter((p) => p.t < 0.8);
if (hp <= 0) { hp = 0; over = true; }
}
function drawHud() {
ctx.fillStyle = 'rgba(0,0,0,0.55)';
ctx.fillRect(0, 0, W, 32);
ctx.textBaseline = 'middle';
ctx.font = 'bold 14px monospace';
ctx.textAlign = 'left';
ctx.fillStyle = '#fff';
ctx.fillText(`SCORE ${String(score).padStart(6, '0')}`, 10, 16);
ctx.textAlign = 'center';
const t = Math.floor(time);
ctx.fillText(`${Math.floor(t / 60)}:${String(t % 60).padStart(2, '0')}`, W / 2, 16);
// health bar: frame, trailing ghost, real value
const bx = W - 130, bw = 120;
ctx.fillStyle = '#333'; ctx.fillRect(bx, 10, bw, 12);
ctx.fillStyle = '#fff8'; ctx.fillRect(bx, 10, Math.round(bw * ghostHp / 100), 12);
ctx.fillStyle = hurt > 0 && Math.floor(hurt * 10) % 2 ? '#fff' : hp > 30 ? '#66bb6a' : '#ef5350';
ctx.fillRect(bx, 10, Math.round(bw * hp / 100), 12);
ctx.strokeStyle = '#fff'; ctx.strokeRect(bx + 0.5, 10.5, bw - 1, 11);
}
function draw() {
ctx.fillStyle = '#16213e';
ctx.fillRect(0, 0, W, H);
ctx.fillStyle = '#ffd54f';
ctx.beginPath(); ctx.arc(coin[0], coin[1], 7, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = '#ef5350';
ctx.beginPath(); ctx.arc(drone.x, drone.y, drone.r, 0, Math.PI * 2); ctx.fill();
if (!(hurt > 0 && Math.floor(hurt * 12) % 2)) {
ctx.fillStyle = '#4fc3f7';
ctx.fillRect(Math.round(player.x), Math.round(player.y), player.s, player.s);
}
ctx.font = 'bold 12px monospace';
ctx.textAlign = 'center';
for (const p of popups) {
ctx.globalAlpha = 1 - p.t / 0.8;
ctx.fillStyle = '#ffd54f';
ctx.fillText('+10', p.x, Math.round(p.y - 12 - p.t * 30));
}
ctx.globalAlpha = 1;
drawHud();
if (over) banner('GAME OVER', `score ${score}, press Enter to play again`);
}
run(update, draw, 'Arrows move. Grab coins, dodge the drone');
</script>The playfield starts below the 32-pixel HUD strip, so the HUD never hides the player. The pop-ups and the blinking player are small touches, but they tell the player instantly what just happened.
Menus as a list of items
A menu is a state of the game with its own update and draw. Keep the items in an array, keep a selected index, and let each item decide what Left/Right or Enter does. This makes adding a new option a one-line change.
<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 settings = { difficulty: 1, sound: true };
const DIFF = ['Easy', 'Normal', 'Hard'];
const menu = [
{ label: () => 'Start game', enter: () => { state = 'play'; } },
{ label: () => `Difficulty: ${DIFF[settings.difficulty]}`, change: (d) => { settings.difficulty = (settings.difficulty + d + 3) % 3; } },
{ label: () => `Sound: ${settings.sound ? 'On' : 'Off'}`, change: () => { settings.sound = !settings.sound; } },
];
let state = 'menu', selected = 0, blink = 0, x = 0;
function update(dt) {
blink += dt;
if (state === 'menu') {
if (pressed.has('ArrowDown')) selected = (selected + 1) % menu.length;
if (pressed.has('ArrowUp')) selected = (selected - 1 + menu.length) % menu.length;
const item = menu[selected];
if (pressed.has('ArrowLeft')) item.change?.(-1);
if (pressed.has('ArrowRight')) item.change?.(1);
if (pressed.has('Enter') || pressed.has('Space')) (item.enter ?? item.change)?.(1);
} else {
x = (x + (60 + settings.difficulty * 80) * dt) % W;
if (pressed.has('Escape') || pressed.has('KeyM')) state = 'menu';
}
}
function draw() {
ctx.fillStyle = '#1a1033';
ctx.fillRect(0, 0, W, H);
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
if (state === 'menu') {
ctx.fillStyle = '#ffd54f';
ctx.font = 'bold 28px system-ui, sans-serif';
ctx.fillText('SKY HOPPER', W / 2, 60);
ctx.font = '16px system-ui, sans-serif';
menu.forEach((item, i) => {
const y = 130 + i * 32;
if (i === selected) {
ctx.fillStyle = '#7c4dff';
ctx.fillRect(W / 2 - 110, y - 13, 220, 26);
}
ctx.fillStyle = '#fff';
ctx.fillText((i === selected && item.change ? '< ' : '') + item.label() + (i === selected && item.change ? ' >' : ''), W / 2, y);
});
ctx.fillStyle = '#9fa8da';
ctx.font = '12px system-ui, sans-serif';
ctx.fillText('Up/Down choose, Left/Right change, Enter select', W / 2, H - 20);
} else {
ctx.fillStyle = '#4fc3f7';
ctx.fillRect(Math.round(x), 150, 20, 20);
ctx.fillStyle = '#fff';
ctx.font = '14px system-ui, sans-serif';
ctx.fillText(`Playing on ${DIFF[settings.difficulty]}, sound ${settings.sound ? 'on' : 'off'}`, W / 2, 60);
if (Math.floor(blink * 2) % 2) ctx.fillText('Esc or M: back to the menu', W / 2, 90);
}
}
run(update, draw, 'Arrow keys + Enter');
</script>Tip: Make every menu fully usable with the keyboard and the mouse or touch. For pointer input, store each item's rectangle when you draw it and test clicks against those rectangles; the Mouse & Touch lesson shows how to map pointer coordinates into canvas pixels.
Note: Long text, forms and settings with many options are often easier as real HTML elements placed over the canvas: you get fonts, focus, screen readers and text input for free. Many shipped web games draw the HUD on the canvas and the menus in HTML.
Test yourself
Why is the HUD drawn after ctx.restore() of the camera transform?
- It is faster
- So it stays fixed on screen instead of moving with the camera and shake
- Canvas text only works without transforms
- To make it blurry
What does String(450).padStart(6, '0') return?
'450000''000450''450''0450'
Why clamp the health ratio to 0..1 before computing a bar width?
- Canvas can't draw negative widths
- So damage below zero or overheal never draws the bar outside its frame
- To round the number
- To save memory