The Game Canvas
Before drawing a single sprite, a game needs a stage: a canvas with a fixed game resolution that scales to whatever space the page gives it, stays sharp, and receives the keyboard. This lesson sets that stage and builds the play kit that every game in the course starts with.
Game resolution vs display size
A canvas has two sizes:
| Size | Set with | Meaning |
|---|---|---|
| Drawing buffer (resolution) | the width / height attributes |
How many pixels you draw into. All game coordinates use this size |
| Display size | CSS width / height |
How big the canvas appears on screen. The browser stretches the buffer to fit |
Games pick one resolution and stick to it. This course uses 480 × 270, a 16:9 shape (a quarter of 1920 × 1080 in each direction). Positions such as x = 240 always mean "the middle", however large the canvas appears. CSS then scales the whole picture.
<style>
body { margin: 8px; font: 13px system-ui, sans-serif; background: #fff; }
canvas { border: 1px solid #999; vertical-align: top; margin-right: 8px; }
</style>
<canvas id="a" width="120" height="68" style="width:240px;height:135px"></canvas>
<canvas id="b" width="240" height="135"></canvas>
<p>Left: a 120 × 68 buffer stretched 2× by CSS (blurry). Right: a 240 × 135 buffer shown at its own size (sharp).</p>
<script>
for (const id of ['a', 'b']) {
const c = document.getElementById(id), g = c.getContext('2d');
const s = c.width / 120; // draw the same scene at both resolutions
g.fillStyle = '#1d2333'; g.fillRect(0, 0, c.width, c.height);
g.fillStyle = '#ffb74d'; g.beginPath(); g.arc(40 * s, 34 * s, 18 * s, 0, Math.PI * 2); g.fill();
g.fillStyle = '#fff'; g.font = `${10 * s}px system-ui`; g.fillText('Score 42', 70 * s, 20 * s);
}
</script>The left canvas is blurry because the browser smooths the stretched pixels. Two fixes exist, and games use both:
- Draw at a higher resolution when you want smooth vector-style graphics (see
devicePixelRatiobelow). - Turn smoothing off when you want chunky pixel art: CSS
image-rendering: pixelatedon the canvas, andctx.imageSmoothingEnabled = falsebeforedrawImageof small sprites.
Scaling to fit, keeping the shape
A game should fill its space without being squashed. With a 16:9 game, the display width must be the smaller of "all the width" and "16/9 of the height". CSS can express that directly:
html, body { margin: 0; height: 100%; overflow: hidden; }
canvas {
display: block;
margin: 0 auto; /* centre horizontally */
width: min(100vw, 177.78vh); /* 177.78 = 100 × 16 / 9 */
height: auto; /* the browser keeps the 480:270 shape */
}When the frame is wide, the height wins and you get bars at the sides; when it is narrow (try the Phone width button on a playground), the width wins. The same calculation in JavaScript, useful when you need the scale factor yourself (for example to convert mouse positions):
function fit(viewW, viewH, gameW, gameH) {
const scale = Math.min(viewW / gameW, viewH / gameH);
const w = Math.round(gameW * scale), h = Math.round(gameH * scale);
return { scale: +scale.toFixed(3), w, h, offsetX: Math.floor((viewW - w) / 2), offsetY: Math.floor((viewH - h) / 2) };
}
console.log(fit(834, 280, 480, 270)); // the lesson frame on a laptop
console.log(fit(375, 280, 480, 270)); // the same frame on a phone
console.log(fit(1920, 1080, 480, 270)); // full HD fullscreen: exactly 4x{ scale: 1.037, w: 498, h: 280, offsetX: 168, offsetY: 0 }
{ scale: 0.781, w: 375, h: 211, offsetX: 0, offsetY: 34 }
{ scale: 4, w: 1920, h: 1080, offsetX: 0, offsetY: 0 }
Tip: For pixel art, scale by whole numbers (2×, 3×, 4×) when you can. At 4× every game pixel becomes an exact 4 × 4 block; at 1.037× some pixels are one screen pixel wider than others, which shows up as shimmer when things move.
Sharp text on high-density screens
Phones and many laptops have devicePixelRatio of 2 or 3: one CSS pixel is 2 × 2 or 3 × 3 physical pixels. For crisp vector graphics, make the buffer that much bigger and scale the drawing context, so your game code still thinks in 480 × 270:
const dpr = Math.min(window.devicePixelRatio || 1, 2); // cap it: 3x buffers cost a lot of fill rate
canvas.width = 480 * dpr;
canvas.height = 270 * dpr;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0); // 1 game unit = dpr buffer pixelsPixel-art games usually skip this and rely on image-rendering: pixelated instead.
Getting the keyboard: focus
Keyboard events go to whichever element has focus. A canvas is not focusable by default, and a game inside an <iframe> (like every playground here, or an embed on itch.io) gets no keys at all until the player clicks into it. So:
- give the canvas
tabIndex = 0, which makes it focusable (and reachable with Tab); - call
canvas.focus()onpointerdown; - treat
focus/bluras "playing" / "paused"; - call
preventDefault()on arrow keys and Space, or they also scroll the page around the game.
Try it: the demo shows whether it has focus and which key you pressed last. Press T to switch preventDefault() off and on. With it off, the arrow keys scroll this lesson while you play.
<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; }
</style>
<canvas width="480" height="270"></canvas>
<script>
const cv = document.querySelector('canvas'), ctx = cv.getContext('2d');
let focused = false, last = '(none)', prevent = true;
cv.tabIndex = 0;
cv.addEventListener('pointerdown', () => cv.focus());
cv.addEventListener('focus', () => { focused = true; draw(); });
cv.addEventListener('blur', () => { focused = false; draw(); });
addEventListener('keydown', (e) => {
if (e.code === 'KeyT') prevent = !prevent;
if (prevent && (e.code.startsWith('Arrow') || e.code === 'Space')) e.preventDefault();
last = `code "${e.code}" key "${e.key}"`;
draw();
});
function draw() {
ctx.fillStyle = focused ? '#123524' : '#3a1717';
ctx.fillRect(0, 0, 480, 270);
ctx.fillStyle = '#fff';
ctx.textAlign = 'center';
ctx.font = 'bold 22px system-ui, sans-serif';
ctx.fillText(focused ? 'Focused: keys arrive here' : 'Not focused: click me', 240, 90);
ctx.font = '16px system-ui, sans-serif';
ctx.fillText('Last key: ' + last, 240, 140);
ctx.fillText('preventDefault on arrows/Space: ' + (prevent ? 'ON' : 'OFF') + ' (T toggles)', 240, 180);
}
draw();
</script>Notice the two names each key has. e.code is the physical key (KeyW is the key left of E on any layout, even AZERTY where it prints Z), while e.key is the character it types. Games use e.code for movement keys.
The play kit
Putting it together, here is the block every game in this course starts with. Read it once; later lessons explain the loop part in detail (requestAnimationFrame and the fixed-step loop).
const cv = document.querySelector('canvas'), ctx = cv.getContext('2d');
const W = cv.width, H = cv.height; // 480 x 270 game units
const keys = new Set(), pressed = new Set(); // held now / pressed since the last update
let active = false, idleDrawn = false;
cv.tabIndex = 0; // focusable
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();
if (!e.repeat) pressed.add(e.code); // ignore auto-repeat for "pressed"
keys.add(e.code);
});
addEventListener('keyup', (e) => keys.delete(e.code));
// banner(title, sub) draws a dimmed overlay with text.
// run(update, draw, help) calls update(1/60) 60 times a second while active,
// draws every frame, and shows "Click to play" + help while paused.Clearing keys on blur matters: if the player holds →, clicks outside, and releases the key there, the game never sees the keyup, and the character would run forever.
Test yourself
A canvas has width="480" height="270" and CSS width: 960px. Where is the game coordinate x = 480?
- In the middle of the canvas
- At the right edge of the canvas
- Outside the canvas
- It depends on devicePixelRatio
Which property should a game read to know that the player pressed the key for **move up** on any keyboard layout?
e.key === 'w'e.code === 'KeyW'e.keyCode === 87e.charCode
Why does the play kit clear the keys set on blur?
- To save memory
- A key released while the game is unfocused never sends
keyupto the game, so it would stay "held" - Because
blurresets the canvas - Browsers require it