Drawing Shapes & Text
Games are drawn from scratch every frame: clear the screen, then paint the background, the objects and the score on top. This lesson covers the drawing tools you will use in every game: rectangles, paths, circles, transforms, text and transparency.
Clear, then paint back to front
The canvas has no layers or objects. It is a grid of pixels, and later drawing covers earlier drawing. So a frame is always painted back to front (the painter's algorithm):
<canvas width="480" height="270" style="width:100%;max-width:480px;background:#000"></canvas>
<script>
const ctx = document.querySelector('canvas').getContext('2d');
// 1. background: a sky gradient
const sky = ctx.createLinearGradient(0, 0, 0, 270);
sky.addColorStop(0, '#1a237e');
sky.addColorStop(1, '#f48fb1');
ctx.fillStyle = sky;
ctx.fillRect(0, 0, 480, 270);
// 2. far mountains (a path)
ctx.fillStyle = '#3949ab';
ctx.beginPath();
ctx.moveTo(0, 220);
ctx.lineTo(90, 120); ctx.lineTo(170, 200); ctx.lineTo(260, 100); ctx.lineTo(380, 210); ctx.lineTo(480, 140);
ctx.lineTo(480, 270); ctx.lineTo(0, 270);
ctx.closePath();
ctx.fill();
// 3. ground (rectangles)
ctx.fillStyle = '#2e7d32';
ctx.fillRect(0, 230, 480, 40);
ctx.fillStyle = '#1b5e20';
for (let x = 0; x < 480; x += 32) ctx.fillRect(x, 230, 16, 6); // a simple grass pattern
// 4. the player: a circle with an outline
ctx.beginPath();
ctx.arc(120, 214, 16, 0, Math.PI * 2);
ctx.fillStyle = '#ffca28';
ctx.fill();
ctx.lineWidth = 3;
ctx.strokeStyle = '#5d4037';
ctx.stroke();
// 5. the HUD last, so it is always on top
ctx.fillStyle = '#fff';
ctx.font = 'bold 18px system-ui, sans-serif';
ctx.fillText('Score 120', 12, 26);
</script>Every game in the course starts draw() with a fillRect over the whole canvas. That both clears the last frame and paints the background in one call. Use ctx.clearRect(0, 0, W, H) instead when you want a transparent canvas over a CSS background.
The shape toolbox
| Call | Draws |
|---|---|
fillRect(x, y, w, h) / strokeRect |
Axis-aligned rectangle (fastest shape; no path needed) |
beginPath() then moveTo / lineTo / closePath() |
Polygons: ships, mountains, arrows |
arc(x, y, r, start, end) |
Circles and arcs; angles in radians, Math.PI * 2 is a full turn |
ellipse(x, y, rx, ry, rotation, start, end) |
Ellipses (shadows under characters) |
roundRect(x, y, w, h, radius) |
Rounded rectangles (buttons, health bars) |
fill() / stroke() |
Paint the current path with fillStyle / strokeStyle and lineWidth |
Note: Always call
beginPath()before a new shape. Without it, the newarcis added to the previous path, and the nextfill()repaints all of them.
Transforms: draw around (0, 0), then move it
To draw a rotated ship, don't calculate rotated corner points yourself. Move the origin to the ship, rotate the whole coordinate system, and draw the ship around (0, 0). save() and restore() put the coordinate system back afterwards:
<canvas width="480" height="270" style="width:100%;max-width:480px;background:#0e1018"></canvas>
<script>
const ctx = document.querySelector('canvas').getContext('2d');
function drawShip(x, y, angle, color) {
ctx.save();
ctx.translate(x, y); // origin -> ship centre
ctx.rotate(angle); // radians, clockwise because y points down
ctx.fillStyle = color;
ctx.beginPath();
ctx.moveTo(16, 0); // nose points along +x
ctx.lineTo(-10, -10);
ctx.lineTo(-5, 0);
ctx.lineTo(-10, 10);
ctx.closePath();
ctx.fill();
ctx.restore(); // undo translate + rotate
}
let t = 0;
function frame() {
ctx.fillStyle = '#0e1018';
ctx.fillRect(0, 0, 480, 270);
for (let i = 0; i < 8; i++) {
const a = t + (i * Math.PI) / 4;
// ships orbit the centre and face their direction of travel
drawShip(240 + Math.cos(a) * 100, 135 + Math.sin(a) * 100, a + Math.PI / 2, `hsl(${i * 45}, 80%, 65%)`);
}
drawShip(240, 135, -t * 2, '#fff');
t += 0.01;
requestAnimationFrame(frame);
}
frame();
</script>The order matters: translate then rotate spins the ship in place. rotate then translate would swing it around the canvas origin instead. ctx.scale(-1, 1) mirrors a drawing, which is how one "facing right" sprite also faces left.
Text
ctx.font = 'bold 20px system-ui, sans-serif'; // CSS font syntax
ctx.textAlign = 'center'; // left | center | right (relative to x)
ctx.textBaseline = 'middle'; // top | middle | alphabetic | bottom (relative to y)
ctx.fillText('GAME OVER', W / 2, H / 2);
const width = ctx.measureText('Score 9999').width; // for right-aligned HUDs or boxes behind texttextAlign and textBaseline stay set until you change them, which is a common source of "my score moved" bugs. Set them every time you draw text, or wrap the text drawing in save() / restore().
Transparency and blending
ctx.globalAlpha = 0.5makes everything drawn afterwards half transparent (fading particles, ghosts).- Colors with alpha:
'rgba(0, 0, 0, 0.6)'for a dark overlay behind a pause menu. ctx.globalCompositeOperation = 'lighter'adds colors together, which makes overlapping sparks and explosions glow. Set it back to'source-over'(the default) afterwards.
<canvas width="480" height="270" style="width:100%;max-width:480px;background:#000"></canvas>
<script>
const ctx = document.querySelector('canvas').getContext('2d');
ctx.fillStyle = '#000';
ctx.fillRect(0, 0, 480, 270);
function glowBalls(cx, mode, label) {
ctx.globalCompositeOperation = mode;
const colors = ['#ff1744', '#00e676', '#2979ff'];
colors.forEach((c, i) => {
const a = (i * Math.PI * 2) / 3;
ctx.fillStyle = c;
ctx.globalAlpha = 0.8;
ctx.beginPath();
ctx.arc(cx + Math.cos(a) * 30, 130 + Math.sin(a) * 30, 50, 0, Math.PI * 2);
ctx.fill();
});
ctx.globalAlpha = 1;
ctx.globalCompositeOperation = 'source-over';
ctx.fillStyle = '#fff';
ctx.font = '15px system-ui, sans-serif';
ctx.textAlign = 'center';
ctx.fillText(label, cx, 240);
}
glowBalls(130, 'source-over', "'source-over' (normal)");
glowBalls(350, 'lighter', "'lighter' (additive)");
</script>Test yourself
In what order should a frame be drawn?
- HUD, player, background
- Background first, then objects, then the HUD on top
- Any order: canvas sorts by depth
- Objects first, then clear the screen
Why wrap a rotated drawing in ctx.save() and ctx.restore()?
- To save the image to disk
- So the translate/rotate doesn't affect everything drawn after it
- To make drawing faster
- Because rotate only works inside save()
Two circles are filled with one fill() call even though you meant to fill them separately. What was missing?
closePath()beginPath()before the second circlestroke()save()