Frontend development · Beginner · 25 min
Draw graphics and animate them on an HTML canvas
By Padding · Updated 18 Nov 2026
Modern browsers · HTML canvas 2D API · checked in Chromium 159 with Node.js 26.13
You will draw a small park scene on an HTML canvas with shapes, a path, text and an image, keep it sharp on high-density screens, animate a bouncing ball with time-based movement that pauses for reduced motion, and check the pixels with a Playwright test.
On this page
A <canvas> element is a rectangle of pixels that JavaScript paints into. Unlike HTML or SVG, nothing you draw stays on the page as an element: once a circle is painted, the browser only remembers coloured pixels, not "a circle". That makes canvas fast for scenes that change every frame, such as games, particle effects and charts with thousands of points, and it also means you are responsible for redrawing, sizing and accessibility yourself.
In this tutorial you build a small park scene: sky, floor, a hill, a sun, a label and a tree image, with a red ball that falls and bounces across it. Along the way you scale the canvas so it stays crisp on phone screens, drive the animation from elapsed time rather than frame count, pause it for people who ask for reduced motion, and give screen readers a description. A Playwright test then reads pixels back from the canvas to prove the scene is drawn and the ball moves (or does not) when it should.
Everything here is plain HTML, CSS and JavaScript with no build step. The scene draws locally, so once the page has loaded it costs no further data, which matters to readers on prepaid mobile data.
Step 1 · Add a canvas with a text alternative
Make a demo folder and write the page. The canvas gets a fixed drawing size of 640 by 360 in its attributes, which you replace with a sharper size later, and two kinds of text for people who cannot see it.
mkdir -p ~/canvas-demo
cd ~/canvas-demo
cat > index.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bouncing ball · canvas demo</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<main>
<h1>Bouncing ball</h1>
<canvas id="scene" width="640" height="360" role="img"
aria-label="A red ball bouncing across a green park under a yellow sun, next to a tree">
<p>A red ball bouncing across a green park under a yellow sun, next to a tree.</p>
</canvas>
<button type="button" id="toggle" hidden>Pause animation</button>
</main>
<script src="scene.js"></script>
<script src="main.js"></script>
</body>
</html>
HTML
cat > style.css <<'CSS'
* { box-sizing: border-box; }
body {
margin: 0;
background: #f4f6f8;
color: #16202b;
font-family: system-ui, sans-serif;
line-height: 1.5;
}
main { max-width: 42rem; margin: 0 auto; padding: 1rem; }
canvas {
display: block;
width: 100%;
max-width: 640px;
aspect-ratio: 16 / 9;
background: #ffffff;
border-radius: 0.5rem;
box-shadow: 0 0 0 1px #9aa5b1;
}
button {
margin-top: 0.75rem;
min-height: 2.75rem;
padding: 0 1rem;
font: inherit;
}
CSS
touch scene.js main.jsThe two text alternatives do different jobs:
role="img"andaria-label. To assistive technology a canvas is otherwise an unnamed box. The role and label make it one image with a description, read the same way as an<img>withalttext.- The paragraph inside
<canvas>. This is fallback content. Browsers show it instead of the canvas when they do not support canvas or when scripting is turned off, so the page still says what should be there.
The frame uses box-shadow rather than border on purpose. A border would add to the canvas's on-screen width, and in a later step you size the drawing to exactly that width.
scene.js will hold the drawing functions and main.js the code that runs them. Both are empty for now.
Check it worked
Open index.html in your browser (open index.html on macOS, xdg-open index.html on Linux, or drag the file into a window). You see the heading and an empty white box with a thin grey frame and rounded corners, about twice as wide as it is tall. No button shows yet, because it is hidden.
Step 2 · Draw rectangles, a path and a circle
All drawing goes through a context object: canvas.getContext('2d') returns one with methods such as fillRect and arc. Its coordinates start at the top-left corner, with x growing to the right and y growing downwards.
Write the drawing code in scene units, a 640 by 360 box, so the numbers stay the same whatever size the canvas ends up on screen:
cd ~/canvas-demo
cat > scene.js <<'JS'
// Everything is drawn in scene units: a box 640 wide and 360 tall.
const W = 640;
const H = 360;
const FLOOR_Y = 300;
const BALL_R = 24;
const COLOURS = {
sky: '#cfe3f2',
hill: '#8fb996',
floor: '#2f6b45',
sun: '#f2b632',
ring: '#ffffff',
label: '#ffffff',
text: '#16202b',
ball: '#e4572e',
};
function drawBackground(ctx) {
// Rectangles need no path: one call each.
ctx.fillStyle = COLOURS.sky;
ctx.fillRect(0, 0, W, H);
ctx.fillStyle = COLOURS.floor;
ctx.fillRect(0, FLOOR_Y, W, H - FLOOR_Y);
// A hill: start a path, curve up and down, close it and fill it.
ctx.beginPath();
ctx.moveTo(0, FLOOR_Y);
ctx.quadraticCurveTo(200, 170, 420, FLOOR_Y);
ctx.closePath();
ctx.fillStyle = COLOURS.hill;
ctx.fill();
// The sun: a circle is an arc from 0 to 2π radians. Fill it, then outline it.
ctx.beginPath();
ctx.arc(560, 70, 34, 0, Math.PI * 2);
ctx.fillStyle = COLOURS.sun;
ctx.fill();
ctx.lineWidth = 4;
ctx.strokeStyle = COLOURS.ring;
ctx.stroke();
}
JS
cat > main.js <<'JS'
const canvas = document.getElementById('scene');
const ctx = canvas.getContext('2d');
drawBackground(ctx);
JSThree habits from this code are worth keeping:
- Set the style, then draw.
fillStyle,strokeStyleandlineWidthare settings on the context. They stay set until you change them, so set them right before each shape that needs them. - Begin every path with
beginPath(). A path collects lines and curves until you fill or stroke it. WithoutbeginPath(), the nextfill()repaints every earlier piece of the path as well. - Paint in order, back to front. There are no layers or z-index. The floor goes first, the hill is painted on top of it, and anything drawn later covers what is underneath.
quadraticCurveTo(200, 170, 420, FLOOR_Y) draws a curve from the current point to (420, 300), pulled up towards the control point at (200, 170). The curve never reaches the control point; it peaks at about y 235.
Check it worked
Reload the page. The box now shows a pale blue sky, a dark green strip of floor along the bottom, a light green hill rising from the left edge and a yellow sun with a white ring near the top-right corner.
Step 3 · Add a label and an image
Canvas text is drawn, not laid out: fillText paints the string at a point and does nothing else. It never wraps, so you measure text yourself when its length matters. Add a label with a white pill sized to the text, and a tree drawn from an image file:
cd ~/canvas-demo
cat >> scene.js <<'JS'
function drawLabel(ctx, text) {
ctx.font = '600 28px system-ui, sans-serif';
ctx.textBaseline = 'top';
const width = ctx.measureText(text).width;
// A pill sized from the measured text, so a longer label still fits.
ctx.beginPath();
ctx.roundRect(12, 12, width + 24, 44, 22);
ctx.fillStyle = COLOURS.label;
ctx.fill();
ctx.fillStyle = COLOURS.text;
ctx.fillText(text, 24, 20);
}
const tree = new Image();
tree.src = 'tree.svg';
function drawTree(ctx) {
// Until the file has loaded there is nothing to draw, so skip it.
if (!tree.complete || tree.naturalWidth === 0) return;
ctx.drawImage(tree, 440, 200, 80, 100);
}
JS
cat > tree.svg <<'SVG'
<svg xmlns="http://www.w3.org/2000/svg" width="80" height="100" viewBox="0 0 80 100">
<rect x="34" y="60" width="12" height="40" fill="#7a4b2a"/>
<circle cx="40" cy="40" r="36" fill="#3f8f4f"/>
</svg>
SVG
cat > main.js <<'JS'
const canvas = document.getElementById('scene');
const ctx = canvas.getContext('2d');
function render() {
drawBackground(ctx);
drawTree(ctx);
drawLabel(ctx, 'Bouncing ball');
}
// Images load in the background: draw now, and again once the tree arrives.
tree.addEventListener('load', render);
render();
JStextBaseline = 'top' makes the y in fillText the top of the text rather than its baseline, which is easier to line up with a box. drawImage(tree, 440, 200, 80, 100) places the image with its top-left corner at (440, 200) and scales it to 80 by 100 scene units.
The image can only be drawn after it has loaded. Calling drawImage too early draws nothing and throws no error, which is a common reason for "my image does not show". That is why drawTree checks first and render runs again on the load event.
If your interface is translated, labels change length: a short English word can be much longer in French or Swahili. Measure with measureText as above, or pass a fourth maxWidth argument to fillText, which squeezes the text to fit. Also check that the font you name has the characters you need, such as the dotted letters in Yoruba (ẹ, ọ, ṣ); a missing glyph falls back to another font or shows as a box.
Check it worked
Reload. A white rounded pill in the top-left corner reads Bouncing ball in dark semi-bold text, with even space on both sides of the words. A round green tree with a brown trunk stands on the floor to the right of the hill. Change the label to Bouncing ball in the park in main.js and reload: the pill grows to fit. Change it back.
Step 4 · Keep the drawing sharp on high-density screens
The canvas has two sizes. Its bitmap size comes from the width and height attributes, 640 by 360 pixels. Its display size comes from CSS, up to 640 CSS pixels wide. On a phone or laptop where one CSS pixel covers two or three physical pixels, the browser stretches a 640-pixel bitmap over 1,280 or more device pixels, and text and edges look soft.
The fix is to make the bitmap as large as the physical pixels it covers, then scale the context so your scene units still fit the box. window.devicePixelRatio tells you how many physical pixels make one CSS pixel. Replace main.js:
cd ~/canvas-demo
cat > main.js <<'JS'
const canvas = document.getElementById('scene');
const ctx = canvas.getContext('2d');
function resize() {
const ratio = window.devicePixelRatio || 1;
const cssWidth = canvas.getBoundingClientRect().width;
canvas.width = Math.round(cssWidth * ratio);
canvas.height = Math.round((cssWidth * ratio * H) / W);
// Setting width or height clears the canvas and resets the context,
// so set the scale afterwards: one scene unit becomes `scale` pixels.
const scale = canvas.width / W;
ctx.setTransform(scale, 0, 0, scale, 0, 0);
}
function render() {
drawBackground(ctx);
drawTree(ctx);
drawLabel(ctx, 'Bouncing ball');
}
window.addEventListener('resize', () => {
resize();
render();
});
tree.addEventListener('load', render);
resize();
render();
JSsetTransform(scale, 0, 0, scale, 0, 0) multiplies every coordinate by scale, so fillRect(0, 0, 640, 360) still covers the whole canvas, however many pixels it now has. The resize listener also catches browser zoom in Chrome and Edge, which changes devicePixelRatio.
A bigger bitmap costs memory and drawing time, roughly four times as much at a ratio of 2. For a scene this size that is no problem, even on a low-end Android phone. For a full-screen canvas on such a phone, you can cap the ratio, for example with Math.min(window.devicePixelRatio, 2), and accept slightly softer edges for a smoother frame rate.
Check it worked
Reload, open the developer tools console (F12, or Option+Command+I on a Mac) and run document.getElementById('scene').width. On a standard screen it prints the canvas's CSS width, such as 640; on a high-density screen it prints two or three times that. Zoom in with Ctrl and + (Command and + on a Mac): the label edges stay crisp instead of turning blurry, and the scene still fills its frame. Narrow the window: the scene shrinks with it and keeps its shape.
Step 5 · Animate a bouncing ball with requestAnimationFrame
Animation on a canvas is a loop: work out where things are now, clear, draw the whole scene again, and repeat. requestAnimationFrame(callback) asks the browser to call your function right before it next paints the screen, usually matching the display's refresh rate, and passes it a timestamp in milliseconds.
The refresh rate is not fixed: many screens run at 60 frames a second, some phones at 90 or 120, and a busy low-end phone drops frames. If the ball moved a fixed number of pixels per frame, its speed would change from device to device. Instead, move it by speed multiplied by the seconds since the last frame, so it covers the same distance per second everywhere.
First add a function that draws the ball:
cd ~/canvas-demo
cat >> scene.js <<'JS'
function drawBall(ctx, x, y) {
ctx.beginPath();
ctx.arc(x, y, BALL_R, 0, Math.PI * 2);
ctx.fillStyle = COLOURS.ball;
ctx.fill();
}
JSThen replace main.js with the loop. Speeds are in scene units per second, and gravity adds to the downward speed every second:
cd ~/canvas-demo
cat > main.js <<'JS'
const canvas = document.getElementById('scene');
const ctx = canvas.getContext('2d');
const toggle = document.getElementById('toggle');
const GRAVITY = 900; // scene units per second, added to the speed each second
const BOUNCE = 0.82; // share of the speed kept after hitting the floor
const ball = { x: 80, y: 100, vx: 160, vy: 0 };
let running = false;
let frameId = 0;
let lastTime = null;
function resize() {
const ratio = window.devicePixelRatio || 1;
const cssWidth = canvas.getBoundingClientRect().width;
canvas.width = Math.round(cssWidth * ratio);
canvas.height = Math.round((cssWidth * ratio * H) / W);
const scale = canvas.width / W;
ctx.setTransform(scale, 0, 0, scale, 0, 0);
}
function update(dt) {
ball.vy += GRAVITY * dt;
ball.x += ball.vx * dt;
ball.y += ball.vy * dt;
if (ball.y > FLOOR_Y - BALL_R) {
ball.y = FLOOR_Y - BALL_R;
ball.vy = -ball.vy * BOUNCE;
// Once the bounces get small, kick the ball up again so the scene keeps going.
if (Math.abs(ball.vy) < 120) ball.vy = -520;
}
if (ball.x > W - BALL_R) {
ball.x = W - BALL_R;
ball.vx = -ball.vx;
}
if (ball.x < BALL_R) {
ball.x = BALL_R;
ball.vx = -ball.vx;
}
}
function render() {
ctx.clearRect(0, 0, W, H);
drawBackground(ctx);
drawTree(ctx);
drawLabel(ctx, 'Bouncing ball');
drawBall(ctx, ball.x, ball.y);
}
function frame(now) {
// Seconds since the last frame, capped so a long gap cannot fling the ball.
const dt = lastTime === null ? 0 : Math.min((now - lastTime) / 1000, 0.05);
lastTime = now;
update(dt);
render();
frameId = requestAnimationFrame(frame);
}
function play() {
if (running) return;
running = true;
lastTime = null;
toggle.textContent = 'Pause animation';
frameId = requestAnimationFrame(frame);
}
function pause() {
running = false;
cancelAnimationFrame(frameId);
toggle.textContent = 'Play animation';
render();
}
window.addEventListener('resize', () => {
resize();
render();
});
tree.addEventListener('load', render);
resize();
render();
play();
JSHow the loop fits together:
frameasks for the next frame itself. Each call ends withrequestAnimationFrame(frame), so the loop runs untilcancelAnimationFramestops it. Keeping the returned id inframeIdis what makes stopping possible.dtis capped at 0.05 seconds. Browsers pauserequestAnimationFramein background tabs, which also saves battery. When the reader comes back, the gap since the last frame may be minutes; without the cap the ball would jump straight through the floor.lastTime = nullon play gives the first frame a gap of zero for the same reason.- Every frame clears and redraws everything.
clearRectwipes the canvas, then the whole scene is painted again with the ball in its new place. Here the sky already covers every pixel, soclearRectis belt and braces. Keep it anyway: the day you draw on a transparent background, forgetting to clear leaves a smear of old frames.
Check it worked
Reload. The red ball drops from the top-left, bounces on the floor, rolls across in arcs, rebounds off the right edge and comes back, and never stops. To see why clearing matters, put // in front of the ctx.clearRect and drawBackground(ctx) lines in render and reload: the ball leaves a thick red trail that never goes away. Remove the // again and reload.
Step 6 · Pause for reduced motion and add a pause button
Some people get dizzy or nauseous from movement on screen, and many operating systems let them ask for less of it (Reduce motion on macOS and iOS, Remove animations on Android, Animation effects on Windows 11). The page can read that request with the prefers-reduced-motion media query. Separately, WCAG 2.2 success criterion 2.2.2 asks that anything which moves on its own for more than five seconds, next to other content, can be paused by the user.
Handle both: start paused when the reader prefers reduced motion, follow the setting if it changes while the page is open, and show a button that pauses and plays. Append to main.js:
cd ~/canvas-demo
cat >> main.js <<'JS'
const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)');
function applyMotionPreference() {
if (reduceMotion.matches) pause();
else play();
}
reduceMotion.addEventListener('change', applyMotionPreference);
toggle.addEventListener('click', () => (running ? pause() : play()));
toggle.hidden = false;
applyMotionPreference();
JSThe play() call at the end of the earlier code still runs first. If reduced motion is on, applyMotionPreference() runs straight after it and pause() cancels the frame it asked for before anything moves, then draws one still frame with the ball in its starting place.
The button's text always says what pressing it will do, Pause animation or Play animation, so it reads correctly to screen reader users as well. Reduced motion means less movement, not none, and here the reader can still choose to watch the ball by pressing Play.
Check it worked
Reload. Under the scene, a button reads Pause animation. Press it: the ball freezes where it is and the button reads Play animation. Press it again and the ball carries on from the same place. Now turn on your system's reduced motion setting and reload: the ball sits still near the top-left and the button reads Play animation. Turn the setting off again without reloading: the ball starts moving.
Step 7 · Test the pixels with Playwright
A canvas has no elements inside it to query, so a test has to look at what was painted. getImageData returns the red, green, blue and alpha value of every pixel, which you can compare with the colours in COLOURS.
Reading pixels needs the page served over HTTP. On a page opened straight from disk, the browser may treat the tree image as coming from another origin, and a canvas that has drawn a cross-origin image refuses getImageData with a SecurityError. So the test starts a tiny file server with Node's built-in http module, on a free port, and stops it at the end.
Install Playwright, which drives a real browser from a script. --with-deps also installs the system libraries Chromium needs on Linux, which can ask for your password:
cd ~/canvas-demo
npm init -y > /dev/null
npm install playwright@1.65.1
npx playwright install --with-deps chromiumThen write the test. It opens the page twice on a phone-sized, double-density screen: once with reduced motion requested, to check the still scene, and once without, to check the animation and the pause button.
cd ~/canvas-demo
cat > test-canvas.mjs <<'JS'
import { chromium } from 'playwright';
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
import { basename, extname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
const dir = fileURLToPath(new URL('.', import.meta.url));
const types = { '.html': 'text/html', '.css': 'text/css', '.js': 'text/javascript', '.svg': 'image/svg+xml' };
const server = createServer(async (req, res) => {
const name = basename(new URL(req.url, 'http://localhost').pathname) || 'index.html';
try {
const body = await readFile(join(dir, name));
res.writeHead(200, { 'content-type': types[extname(name)] ?? 'application/octet-stream' });
res.end(body);
} catch {
res.writeHead(404).end();
}
});
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const url = `http://127.0.0.1:${server.address().port}/`;
const browser = await chromium.launch();
const sameColour = (a, b) => a.every((v, i) => v === b[i]);
const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function openScene(reducedMotion) {
const page = await browser.newPage({
viewport: { width: 390, height: 844 },
deviceScaleFactor: 2,
reducedMotion,
});
await page.goto(url);
// Wait until the tree's leaves are painted: the image has loaded and been drawn.
await page.waitForFunction(() => {
const c = document.getElementById('scene');
const s = c.width / 640;
const d = c.getContext('2d').getImageData(Math.round(480 * s), Math.round(240 * s), 1, 1).data;
return d[0] === 0x3f && d[1] === 0x8f && d[2] === 0x4f;
});
return page;
}
// One pixel, given in scene units, as [r, g, b].
const pixel = (page, x, y) =>
page.evaluate(([x, y]) => {
const c = document.getElementById('scene');
const s = c.width / 640;
const d = c.getContext('2d').getImageData(Math.round(x * s), Math.round(y * s), 1, 1).data;
return [d[0], d[1], d[2]];
}, [x, y]);
// The centre of all pixels in the ball's colour, in canvas pixels.
const findBall = (page) =>
page.evaluate(() => {
const c = document.getElementById('scene');
const { data, width } = c.getContext('2d').getImageData(0, 0, c.width, c.height);
let sx = 0, sy = 0, n = 0;
for (let i = 0; i < data.length; i += 4) {
if (data[i] === 0xe4 && data[i + 1] === 0x57 && data[i + 2] === 0x2e) {
const p = i / 4;
sx += p % width;
sy += Math.floor(p / width);
n++;
}
}
return { x: sx / n, y: sy / n, n, scale: c.width / 640 };
});
const distance = (a, b) => Math.hypot(a.x - b.x, a.y - b.y);
// 1. Reduced motion: a still, complete scene.
const still = await openScene('reduce');
const img = still.getByRole('img', { name: /red ball bouncing/ });
assert.equal(await img.count(), 1, 'canvas has role img and a description');
assert.match(await still.locator('#scene p').textContent(), /red ball bouncing/, 'fallback text is present');
const size = await still.evaluate(() => {
const c = document.getElementById('scene');
return { bitmap: c.width, css: c.getBoundingClientRect().width };
});
assert.equal(size.bitmap, Math.round(size.css * 2), 'bitmap matches device pixels at a ratio of 2');
assert.ok(sameColour(await pixel(still, 400, 30), [0xcf, 0xe3, 0xf2]), 'sky');
assert.ok(sameColour(await pixel(still, 320, 340), [0x2f, 0x6b, 0x45]), 'floor');
assert.ok(sameColour(await pixel(still, 205, 260), [0x8f, 0xb9, 0x96]), 'hill');
assert.ok(sameColour(await pixel(still, 560, 70), [0xf2, 0xb6, 0x32]), 'sun');
assert.ok(sameColour(await pixel(still, 480, 285), [0x7a, 0x4b, 0x2a]), 'tree trunk');
assert.ok(sameColour(await pixel(still, 16, 34), [0xff, 0xff, 0xff]), 'label pill');
const darkInLabel = await still.evaluate(() => {
const c = document.getElementById('scene');
const s = c.width / 640;
const { data } = c.getContext('2d').getImageData(Math.round(24 * s), Math.round(16 * s), Math.round(200 * s), Math.round(40 * s));
let n = 0;
for (let i = 0; i < data.length; i += 4) if (data[i] < 60 && data[i + 1] < 60 && data[i + 2] < 70) n++;
return n;
});
assert.ok(darkInLabel > 100, 'label text is drawn');
const start = await findBall(still);
assert.ok(start.n > 1000, 'ball is drawn');
assert.ok(Math.abs(start.x - 80 * start.scale) < 2 && Math.abs(start.y - 100 * start.scale) < 2, 'ball at its start');
await pause(500);
assert.equal(distance(start, await findBall(still)), 0, 'ball stays still with reduced motion');
await still.getByRole('button', { name: 'Play animation' }).click();
await pause(400);
assert.ok(distance(start, await findBall(still)) > 10, 'Play starts the ball');
await still.getByRole('button', { name: 'Pause animation' }).waitFor();
// 2. No preference: the ball moves, and the button pauses it.
const moving = await openScene('no-preference');
const a = await findBall(moving);
await pause(400);
const b = await findBall(moving);
assert.ok(distance(a, b) > 10, 'ball moves on its own');
await moving.getByRole('button', { name: 'Pause animation' }).click();
const c = await findBall(moving);
await pause(400);
assert.equal(distance(c, await findBall(moving)), 0, 'ball stops when paused');
assert.ok(c.n > 1000, 'paused ball is still drawn');
await browser.close();
server.closeAllConnections();
server.close();
console.log('PASS: scene drawn, ball animates and pauses');
JS
node test-canvas.mjsEach colour check reads a pixel well inside a shape, never on an edge. Edges are anti-aliased, blended with the colour behind them, so their values vary from browser to browser. The label check counts dark pixels rather than matching exact positions, because the font, and so the exact shape of each letter, depends on the fonts installed. Finding the ball by its colour and comparing its centre over time tests the animation without reaching into the page's variables.
Check it worked
The last line of output is PASS: scene drawn, ball animates and pauses. To see the test catch a real mistake, delete the line toggle.hidden = false; from main.js and run node test-canvas.mjs again. The button stays hidden, so the test cannot find a Play animation button to press: after about 30 seconds it stops with a TimeoutError from locator.click naming getByRole('button', { name: 'Play animation' }). Put the line back and the test passes again.
Step 8 · Choose canvas or SVG for the next graphic
You have now drawn the same kind of picture you could build in SVG, so you can feel the difference. SVG keeps every shape as an element: the browser redraws it for you, scales it crisply, styles it with CSS, sends clicks to the shape under the pointer and can give each part its own accessible name. Canvas keeps only pixels: you redraw, rescale and hit-test yourself, and the whole thing is one image to assistive technology. In return, painting thousands of objects or changing every pixel each frame costs far less on canvas, where there is no element per object for the browser to track.
A rule of thumb:
- Use SVG for icons, logos, diagrams and charts with up to a few hundred marks, anything people click or focus part by part, and anything that must print or zoom sharply.
- Use canvas for many thousands of points or particles, games and simulations that redraw every frame, and pixel work such as image filters or drawing tools.
- Mix them when a busy canvas needs controls: draw the dense part on canvas and put buttons, labels and legends in HTML or SVG on top, where they stay real, focusable elements.
Check it worked
Decide canvas or SVG for these three before reading the answers: a row of 12 toolbar icons; a map of 20,000 delivery points that pans with a finger; a seven-day sales bar chart where each bar shows a tooltip on hover and focus. Answers: SVG, because the icons are few and must stay sharp; canvas, because 20,000 elements is a lot for the browser to track as the map moves; SVG, because each bar needs to be focusable and named. If you chose differently, write down the reason, then check it against the three lists above.
Step 9 · Clean up
Remove the demo folder, which also removes the local Playwright install. The browser Playwright downloaded stays in its shared cache; npx playwright uninstall removes that too if you no longer need it.
cd ~
rm -rf ~/canvas-demoCheck it worked
ls ~/canvas-demo reports that there is no such file or directory.
Next steps
- Build icons and a small chart with real elements in draw icons and charts with inline SVG.
- Move interface elements with CSS instead of script, again honouring reduced motion, in animate with CSS and respect reduced motion.
- Let the reader steer the ball with arrow keys after working through handle clicks and key presses with event listeners.
Related tutorials
- Draw icons and a simple chart with inline SVGYou will hand-write SVG icons that take their colour from the surrounding text and carry the right accessible names, then build a responsive bar chart of monthly sales from a JavaScript array, with a visible data table beside it and a browser test that checks both.
- Animate with CSS and respect reduced motionYou will add three purposeful animations to the Larkfield Clinic booking flow with CSS transitions and keyframes, give each one a calmer version for people who ask for less motion, and prove both versions with a browser test.
- Select and change page elements with the DOMYou will build a reading-list page whose script finds, changes, adds and removes elements, then renders the whole list from an array through a template and re-renders it when the array changes.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials