Frontend development · Beginner · 24 min
Draw icons and a simple chart with inline SVG
By Padding · Updated 18 Nov 2026
Modern browsers · SVG 2 and the DOM Living Standard · checked in Chromium 159 with Playwright 1.65.1 on node:26
You 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.
On this page
SVG is a drawing language that sits inside HTML. An icon or a chart written as inline SVG is a handful of text elements in your page: no image request, no icon font, no charting library. It stays sharp at any size, CSS can colour it, JavaScript can build it from data, and screen readers can be told what it means.
In this tutorial you write SVG by hand. You start with rectangles, circles and lines on a 24 by 24 grid and see how the viewBox scales them. You draw a download icon with a path, make it follow the text colour of whatever button it sits in, and give it the right accessible name. Then you build a bar chart of a small bakery's monthly cake sales from a JavaScript array, add a data table with the same numbers, and make the chart fit any screen. A short Playwright script checks the lot in a real browser at the end.
Everything here is a few kilobytes of text, which matters on a low-end Android phone on prepaid data: a hand-built chart costs a fraction of what a charting library does to download and run.
Step 1 · Draw shapes on a 24-unit grid
Make a demo folder and write a page with one small drawing, an ID card icon, shown four times:
mkdir -p ~/svg-demo
cd ~/svg-demo
cat > shapes.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SVG shapes</title>
<style>
body { font-family: system-ui, sans-serif; margin: 1rem; }
figure { display: inline-block; margin: 0 1.5rem 1.5rem 0; vertical-align: top; }
svg { border: 1px dashed #9ba1ac; }
</style>
</head>
<body>
<h1>One drawing, four boxes</h1>
<figure>
<svg id="card-96" width="96" height="96" viewBox="0 0 24 24" fill="none" stroke="#1b1f24" stroke-width="1.5">
<rect x="3" y="5" width="18" height="14" rx="2"/>
<circle cx="9" cy="12" r="2.5"/>
<line x1="14" y1="10" x2="18" y2="10"/>
<line x1="14" y1="14" x2="18" y2="14"/>
</svg>
<figcaption>96 × 96</figcaption>
</figure>
<figure>
<svg id="card-48" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="#1b1f24" stroke-width="1.5">
<rect x="3" y="5" width="18" height="14" rx="2"/>
<circle cx="9" cy="12" r="2.5"/>
<line x1="14" y1="10" x2="18" y2="10"/>
<line x1="14" y1="14" x2="18" y2="14"/>
</svg>
<figcaption>48 × 48</figcaption>
</figure>
<figure>
<svg id="card-24" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#1b1f24" stroke-width="1.5">
<rect x="3" y="5" width="18" height="14" rx="2"/>
<circle cx="9" cy="12" r="2.5"/>
<line x1="14" y1="10" x2="18" y2="10"/>
<line x1="14" y1="14" x2="18" y2="14"/>
</svg>
<figcaption>24 × 24</figcaption>
</figure>
<figure>
<svg id="card-zoom" width="96" height="96" viewBox="0 0 12 12" fill="none" stroke="#1b1f24" stroke-width="1.5">
<rect x="3" y="5" width="18" height="14" rx="2"/>
<circle cx="9" cy="12" r="2.5"/>
<line x1="14" y1="10" x2="18" y2="10"/>
<line x1="14" y1="14" x2="18" y2="14"/>
</svg>
<figcaption>96 × 96, viewBox 0 0 12 12</figcaption>
</figure>
</body>
</html>
HTMLEach shape is placed with numbers on the drawing's own grid, called user units:
<rect>takes its top-left corner (x,y), awidth, aheightand an optional corner radiusrx.<circle>takes a centre (cx,cy) and a radiusr.<line>runs from (x1,y1) to (x2,y2).
The y axis points down, as it does for page layout: y 5 is near the top, y 19 near the bottom. fill="none" and stroke on the <svg> are inherited by every shape inside, so you set them once.
Two attributes on the <svg> decide how big those units are on screen. width and height are the size of the box on the page, in CSS pixels. viewBox="0 0 24 24" says which part of the grid to show in that box: start at (0, 0) and take 24 units across and 24 down. The browser scales that window to fill the box. In a 96-pixel box one unit is 4 pixels; in a 24-pixel box it is 1 pixel. Stroke widths are in user units too, so the lines thicken as the box grows.
The last copy keeps the 96-pixel box but asks for a 12 by 12 window. The browser zooms in: you see only the top-left quarter of the card, twice as large, and everything outside the window is cut off.
Check it worked
Open shapes.html in your browser (open shapes.html on macOS, xdg-open shapes.html on Linux, or drag the file into a window). You see four dashed boxes. The first three hold the same rounded card with a circle and two short lines, at three sizes, all equally sharp. The fourth shows a close-up of the card's top-left corner and part of the circle. Change the first copy's viewBox to 0 0 48 48 and reload: the card shrinks into the top-left quarter of its box, because the window now covers twice as much grid.
Step 2 · Draw a download icon with a path
Rectangles and circles cover a lot, but most icons are paths. A <path> takes one attribute, d, holding a list of drawing commands. Three are enough for many icons:
M x ymoves the pen to a point without drawing.L x ydraws a straight line from the pen to a point.Zcloses the current shape back to its lastM.
A download icon is a downward arrow over a tray. On the 24-unit grid, the arrow's shaft goes from (12, 4) to (12, 15), its head is two lines meeting at (12, 15), and the tray is a line along the bottom:
Write a page that shows the icon large, then uses it in three buttons:
cd ~/svg-demo
cat > icons.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SVG icons</title>
<link rel="stylesheet" href="icons.css">
</head>
<body>
<main>
<h1>Download icons</h1>
<svg class="preview" width="96" height="96" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M12 4 L12 15 M7 10 L12 15 L17 10 M4 20 L20 20"/>
</svg>
<p class="actions">
<button type="button" class="primary">
<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M12 4 L12 15 M7 10 L12 15 L17 10 M4 20 L20 20"/>
</svg>
Download report
</button>
<button type="button" class="quiet">
<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M12 4 L12 15 M7 10 L12 15 L17 10 M4 20 L20 20"/>
</svg>
Download receipt
</button>
<button type="button" class="primary icon-only">
<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" role="img" aria-labelledby="csv-title">
<title id="csv-title">Download CSV</title>
<path d="M12 4 L12 15 M7 10 L12 15 L17 10 M4 20 L20 20"/>
</svg>
</button>
</p>
</main>
</body>
</html>
HTML
touch icons.cssThe whole icon is one path with three pieces, because each M starts a new piece without a line between them. stroke-linecap="round" and stroke-linejoin="round" round off the ends and the corner of the arrow head, which reads better at small sizes. The icons in the buttons have no width or height attributes; CSS sizes them in the next step.
Check it worked
Open icons.html. Above the buttons you see a large black arrow pointing down at a horizontal line, with round ends. The buttons below look like plain browser buttons, and their icons are far larger than the button text, because there is no CSS yet to size them. Change L17 10 in the preview's path to L17 4 and reload: the right half of the arrow head now runs up to the top, which shows you exactly which point that command draws to. Change it back.
Step 3 · Make the icons follow the text colour
Every icon in icons.html uses stroke="currentColor". currentColor is a CSS keyword meaning "the value of color on this element", and color is inherited. So the icon takes the text colour of whatever it sits in, and you never colour icons separately. Write the stylesheet:
cd ~/svg-demo
cat > icons.css <<'CSS'
:root {
--ink: #1b1f24;
--muted: #5a6270;
--accent: #0f5e5a;
}
* { box-sizing: border-box; }
body {
margin: 0;
color: var(--ink);
font-family: system-ui, sans-serif;
line-height: 1.5;
}
main { max-width: 40rem; margin: 0 auto; padding: 1rem; }
.actions { display: flex; flex-wrap: wrap; gap: 0.75rem; }
button {
display: inline-flex;
align-items: center;
gap: 0.5rem;
min-height: 2.75rem;
padding: 0.5rem 1rem;
border: 1px solid currentColor;
border-radius: 0.5rem;
background: #ffffff;
font: inherit;
cursor: pointer;
}
button.primary { color: var(--accent); }
button.quiet { color: var(--muted); }
button.quiet:hover,
button.quiet:focus-visible { color: var(--ink); }
button.icon-only { padding: 0.5rem 0.75rem; }
.icon {
width: 1.25em;
height: 1.25em;
flex: none;
}
CSSThe two buttons with the primary class are teal, the quiet one is grey and turns near-black on hover or keyboard focus. Only the buttons have colours; their icons follow. The icon size is in em, so a button with larger text gets a larger icon without another rule.
Because the button's border also uses currentColor, the border, the text and the icon change together. The same trick works for links, navigation items and dark mode: change color and every icon inside comes with it.
Check it worked
Reload icons.html. The large preview arrow is near-black, the colour of the body text. Download report has teal text, border and arrow; the icon-only button has a teal border and arrow. Download receipt is grey; hold the pointer over it and the text, border and arrow all turn near-black at once. Change --accent to #8a3b12 and reload: both primary buttons and their icons turn brown.
Step 4 · Give each icon the right accessible name
An icon either adds meaning, or it repeats what the text next to it already says. The markup handles the two cases differently.
Decorative icons get aria-hidden="true". In Download report and Download receipt, the words already name the button. If the icon were exposed too, some screen readers would announce an extra unnamed image. aria-hidden="true" removes the SVG from the accessibility tree, so the button is announced as "Download report, button" and nothing more. The large preview is hidden the same way, since it is only there for you to look at.
Icons that carry the meaning get role="img" and a name. The third button has no visible text, so the icon is the only thing that can name it. In the markup:
role="img"tells assistive technology to treat the whole SVG as one image, rather than a group of shapes.<title id="csv-title">Download CSV</title>is the text alternative. It must be the first child of the<svg>. Most desktop browsers also show it as a tooltip on hover.aria-labelledby="csv-title"points at the title explicitly, which gives a consistent name across browsers and screen readers.
The button takes its name from its content, so it is announced as "Download CSV, button". Another common pattern puts aria-label="Download CSV" on the <button> and aria-hidden="true" on the icon; either works, as long as the name says what the button does, not what the icon looks like ("Download CSV", not "Arrow pointing down").
If your interface is offered in several languages, for example English, French and Hausa, translate the <title> text with the rest of the page. An icon name is page text, even though most people never see it.
Check it worked
Open your browser's developer tools on icons.html and find the accessibility pane (Accessibility in Chrome and Edge's Elements panel, the Accessibility tab in Firefox). Select the icon-only button: its name is Download CSV. Select Download report: its name is Download report, and the SVG inside it does not appear in the accessibility tree. Hold the pointer over the icon-only button for a second: a small Download CSV tooltip appears.
Step 5 · Build a bar chart from an array
Now the chart. The bakery sold this many cakes a month in the first half of 2026: January 120, February 95, March 140, April 180, May 160, June 210. Write the page with an empty <svg> for the chart and an empty table for later:
cd ~/svg-demo
cat > chart.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Cakes sold per month</title>
<link rel="stylesheet" href="chart.css">
<script src="chart.js" defer></script>
</head>
<body>
<main>
<h1>Cakes sold per month</h1>
<figure class="chart">
<svg id="sales-chart" width="480" height="300" viewBox="0 0 480 300" role="img" aria-labelledby="sales-title">
<title id="sales-title">Bar chart of cakes sold per month, January to June 2026. The same figures are in the table below.</title>
</svg>
<figcaption>Sales rose from 120 cakes in January to 210 in June, with a dip in February.</figcaption>
</figure>
<table id="sales-table">
<caption>Cakes sold per month, January to June 2026</caption>
<thead>
<tr><th scope="col">Month</th><th scope="col">Cakes sold</th></tr>
</thead>
<tbody></tbody>
</table>
</main>
</body>
</html>
HTMLThen the script. The important line is document.createElementNS. SVG elements live in their own namespace, http://www.w3.org/2000/svg. document.createElement('rect') would create an HTML element that happens to be called rect, which the browser does not draw. createElementNS with the SVG namespace creates a real SVG rectangle.
cd ~/svg-demo
cat > chart.js <<'JS'
const sales = [
{ month: 'Jan', name: 'January', value: 120 },
{ month: 'Feb', name: 'February', value: 95 },
{ month: 'Mar', name: 'March', value: 140 },
{ month: 'Apr', name: 'April', value: 180 },
{ month: 'May', name: 'May', value: 160 },
{ month: 'Jun', name: 'June', value: 210 },
];
const SVG_NS = 'http://www.w3.org/2000/svg';
// The drawing is 480 by 300 user units, matching the viewBox.
const width = 480;
const height = 300;
const margin = { top: 30, right: 16, bottom: 36, left: 16 };
const plotWidth = width - margin.left - margin.right; // 448
const plotHeight = height - margin.top - margin.bottom; // 234
const baseline = margin.top + plotHeight; // y of the bottom axis: 264
const band = plotWidth / sales.length; // horizontal space per month
const barWidth = band * 0.6; // the bar fills 60% of its band
const max = Math.max(...sales.map((d) => d.value));
// Create an SVG element with attributes and optional text.
function svgEl(tag, attrs, text) {
const el = document.createElementNS(SVG_NS, tag);
for (const [key, val] of Object.entries(attrs)) {
el.setAttribute(key, val);
}
if (text !== undefined) el.textContent = text;
return el;
}
const chart = document.getElementById('sales-chart');
const bars = svgEl('g', { class: 'bars' });
sales.forEach((d, i) => {
const barHeight = (d.value / max) * plotHeight;
const x = margin.left + i * band + (band - barWidth) / 2;
const y = baseline - barHeight; // y grows downwards, so the top of the bar is above the baseline
const centre = x + barWidth / 2;
bars.append(
svgEl('rect', { class: 'bar', x, y, width: barWidth, height: barHeight, 'data-month': d.month }),
svgEl('text', { class: 'value', x: centre, y: y - 8, 'text-anchor': 'middle' }, d.value),
svgEl('text', { class: 'month', x: centre, y: baseline + 24, 'text-anchor': 'middle' }, d.month),
);
});
bars.append(svgEl('line', { class: 'axis', x1: margin.left, y1: baseline, x2: width - margin.right, y2: baseline }));
chart.append(bars);
JSBecause the y axis points down, a bar cannot start at the baseline and grow upwards. Instead each bar's top edge is placed at baseline - barHeight, and its height runs down to the baseline. The tallest month, June, gets the full plot height; every other bar is scaled against it.
Add the styles. The bars use fill: currentColor, so the chart's colour is set once, on the figure, exactly like the icons:
cd ~/svg-demo
cat > chart.css <<'CSS'
:root {
--ink: #1b1f24;
--muted: #5a6270;
--accent: #0f5e5a;
}
* { box-sizing: border-box; }
body {
margin: 0;
color: var(--ink);
font-family: system-ui, sans-serif;
line-height: 1.5;
}
main { max-width: 40rem; margin: 0 auto; padding: 1rem; }
.chart { margin: 0 0 2rem; color: var(--accent); }
.chart figcaption { color: var(--muted); font-size: 0.875rem; margin-top: 0.5rem; }
.chart .bar { fill: currentColor; }
.chart text { fill: var(--ink); font-size: 18px; font-variant-numeric: tabular-nums; }
.chart .month { fill: var(--muted); }
.chart .axis { stroke: var(--muted); stroke-width: 2; }
CSSCheck it worked
Open chart.html. You see six teal bars on a grey baseline, rising from left to right with a dip at the second bar. Each bar has its number above it and a month abbreviation below it. June is the tallest bar and its top almost touches the top of the drawing. Change February's value in chart.js to 250 and reload: February becomes the tallest and the others shrink to fit. Put it back to 95.
Step 6 · Add the data as a table
The chart's role="img" and title tell a screen reader user what the chart is, and the caption gives the trend. They cannot give the six exact figures, and nor should they: a long title is tiring to listen to. A table is the alternative that works for everyone, including sighted readers who want exact numbers, people using a screen magnifier, and anyone copying the data. Build it from the same array, so the chart and the table can never disagree:
cd ~/svg-demo
cat >> chart.js <<'JS'
// The same figures as a table, from the same array.
const tbody = document.querySelector('#sales-table tbody');
for (const d of sales) {
const row = tbody.insertRow();
const th = document.createElement('th');
th.scope = 'row';
th.textContent = d.name;
row.append(th);
row.insertCell().textContent = d.value;
}
JS
cat >> chart.css <<'CSS'
table { border-collapse: collapse; width: 100%; max-width: 24rem; }
caption { text-align: start; font-weight: 600; margin-bottom: 0.5rem; }
th, td { padding: 0.375rem 0.75rem; border-bottom: 1px solid #d5d9df; text-align: start; }
td { text-align: end; font-variant-numeric: tabular-nums; }
CSSEach month is a row header (<th scope="row">), so a screen reader reading a figure also reads its month. The table uses full month names, which are clearer when read aloud than "Jan" or "Jun". If you serve the page in other languages, Intl.DateTimeFormat can produce month names for the reader's locale, so you do not have to keep a list per language.
If the figures come from a server, write the table into the HTML there and let the script read it, so the data is on the page even if the script fails to load on a weak connection.
Check it worked
Reload chart.html. Under the chart is a table titled Cakes sold per month, January to June 2026 with six rows from January (120) to June (210), the numbers right-aligned. Each figure matches the number above the bar for that month.
Step 7 · Make the chart fit any screen
The <svg> still has a fixed width="480". Narrow your browser window, or open the developer tools' device mode at a phone width such as 390 pixels: the chart is wider than the screen and the page scrolls sideways.
Tell CSS to size the SVG to the width of the figure around it and let the height follow:
cd ~/svg-demo
cat >> chart.css <<'CSS'
.chart svg {
display: block;
width: 100%;
height: auto;
}
CSSCSS width and height override the attributes, so the box now takes the full width of the figure. The viewBox has not changed, so the browser scales the whole 480 by 300 drawing into the new box, and height: auto keeps the same 480:300 shape. The attributes still matter: they give the SVG a sensible size before the stylesheet loads, and the browser uses their ratio for height: auto.
When the box is a different shape from the viewBox, SVG does not stretch the drawing. Its default, preserveAspectRatio="xMidYMid meet", scales it to fit and centres it, leaving space at the sides or the top and bottom.
Scaling has a cost: the text shrinks with everything else. At 390 pixels wide the drawing is about three quarters of its designed size, so the 18-unit labels show at about 13 pixels. That is why the labels use 18 rather than a more usual 14. If you make the drawing wider, raise the font size with it, or the labels become unreadable on phones.
Check it worked
Reload chart.html and make the window narrow. The chart shrinks with the window, keeps its shape, and the page no longer scrolls sideways. Widen the window again: the chart grows until it fills the page's content column (40rem less the padding) and stays sharp at every size. The month labels stay readable at the narrowest width.
Step 8 · Test the icons and the chart in a browser, then clean up
A short script can check everything you just looked at by eye, every time someone changes the code. 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 ~/svg-demo
npm init -y > /dev/null
npm install playwright@1.65.1
npx playwright install --with-deps chromiumWrite the test. It checks the viewBox scaling, that icons take their button's colour, the accessible names, the bar heights against the data, the table, and the chart's size at phone and desktop widths:
cd ~/svg-demo
cat > test-svg.mjs <<'JS'
import { chromium } from 'playwright';
import assert from 'node:assert/strict';
const fileUrl = (name) => new URL(`./${name}`, import.meta.url).href;
const near = (a, b, tolerance, message) => assert.ok(Math.abs(a - b) <= tolerance, `${message}: ${a} vs ${b}`);
const browser = await chromium.launch();
const page = await browser.newPage({ viewport: { width: 1000, height: 800 } });
// 1. viewBox: the same drawing scales with the box; a smaller viewBox zooms in.
await page.goto(fileUrl('shapes.html'));
const rectWidth = (id) => page.locator(`#${id} rect`).evaluate((r) => r.getBoundingClientRect().width);
const w96 = await rectWidth('card-96');
const w24 = await rectWidth('card-24');
const zoom = await rectWidth('card-zoom');
near(w96 / w24, 4, 0.1, '96px box draws the card 4 times larger than the 24px box');
near(zoom / w96, 2, 0.1, 'viewBox 0 0 12 12 doubles the scale');
// 2. Icons take their colour from the button and have the right names.
await page.goto(fileUrl('icons.html'));
const strokeMatchesButton = (button) =>
button.evaluate((b) => getComputedStyle(b.querySelector('path')).stroke === getComputedStyle(b).color);
const report = page.getByRole('button', { name: 'Download report', exact: true });
const receipt = page.getByRole('button', { name: 'Download receipt', exact: true });
const csv = page.getByRole('button', { name: 'Download CSV', exact: true });
assert.ok(await strokeMatchesButton(report), 'report icon follows button colour');
assert.ok(await strokeMatchesButton(csv), 'CSV icon follows button colour');
assert.ok(await strokeMatchesButton(receipt), 'receipt icon follows button colour');
assert.equal(await receipt.evaluate((b) => getComputedStyle(b).color), 'rgb(90, 98, 112)', 'quiet button is grey');
await receipt.hover();
assert.equal(await receipt.evaluate((b) => getComputedStyle(b).color), 'rgb(27, 31, 36)', 'quiet button darkens on hover');
assert.ok(await strokeMatchesButton(receipt), 'receipt icon darkens with it');
// Only the icon-only button's SVG is exposed as an image.
assert.equal(await page.getByRole('img').count(), 1, 'only the icon-only button exposes an image');
await page.getByRole('img', { name: 'Download CSV' }).waitFor();
// 3. The chart: bars match the data, and the table holds the same figures.
await page.goto(fileUrl('chart.html'));
await page.getByRole('img', { name: /Bar chart of cakes sold per month/ }).waitFor();
const bars = await page.locator('#sales-chart rect.bar').evaluateAll((rects) =>
rects.map((r) => ({ month: r.dataset.month, height: Number(r.getAttribute('height')), y: Number(r.getAttribute('y')) })));
assert.equal(bars.length, 6);
const june = bars.find((b) => b.month === 'Jun');
near(june.height, 234, 0.01, 'June fills the plot height');
near(june.y, 30, 0.01, 'June starts at the top margin');
const feb = bars.find((b) => b.month === 'Feb');
near(feb.height / june.height, 95 / 210, 0.001, 'bar heights are proportional to the data');
for (const b of bars) near(b.y + b.height, 264, 0.01, `${b.month} sits on the baseline`);
const svgTag = await page.locator('#sales-chart rect.bar').first().evaluate((r) => r.namespaceURI);
assert.equal(svgTag, 'http://www.w3.org/2000/svg');
const table = page.getByRole('table', { name: 'Cakes sold per month, January to June 2026' });
assert.equal(await table.locator('tbody tr').count(), 6);
assert.equal(await table.getByRole('row', { name: 'June 210' }).count(), 1);
assert.equal(await table.getByRole('row', { name: 'February 95' }).count(), 1);
// 4. Responsive: the chart keeps its 480:300 shape and fits the screen.
const chartBox = () => page.locator('#sales-chart').evaluate((s) => {
const r = s.getBoundingClientRect();
return { width: r.width, height: r.height };
});
const wide = await chartBox();
assert.ok(wide.width > 480, `chart grows on a wide screen (${wide.width})`);
near(wide.height / wide.width, 300 / 480, 0.01, 'shape kept on a wide screen');
await page.setViewportSize({ width: 390, height: 844 });
const narrow = await chartBox();
assert.ok(narrow.width <= 390 - 32, `chart fits a phone screen (${narrow.width})`);
near(narrow.height / narrow.width, 300 / 480, 0.01, 'shape kept on a phone');
const overflow = await page.evaluate(() => document.documentElement.scrollWidth > document.documentElement.clientWidth);
assert.equal(overflow, false, 'no sideways scroll');
const labelSize = 18 * (narrow.width / 480);
assert.ok(labelSize >= 12, `labels stay at least 12px on a phone (${labelSize.toFixed(1)})`);
await browser.close();
console.log('PASS: icons and chart checked');
JS
node test-svg.mjsThe test finds elements by role and accessible name, as a screen reader would, so renaming a title or dropping aria-hidden breaks it. It reads the bar heights straight from the SVG and compares them with the numbers in the array.
When you have finished, 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 ~/svg-demoCheck it worked
Before the clean-up, the last line of output was PASS: icons and chart checked. To see the test fail for the right reason, delete aria-hidden="true" from the Download report icon in icons.html and run node test-svg.mjs again: it stops with an AssertionError whose message reads only the icon-only button exposes an image. After the clean-up, ls ~/svg-demo reports that there is no such file or directory.
Next steps
- Draw pixels instead of shapes, and animate them, in draw graphics and animate them on an HTML canvas.
- Learn the DOM methods the chart script relies on in select and change page elements with the DOM.
- Make the data table work on small screens with build a responsive HTML table.
- Check the icons and chart with real assistive technology in test a page for accessibility with axe and a screen reader.
Related tutorials
- Draw graphics and animate them on an HTML canvasYou 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.
- 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.
- Build a responsive HTML tableYou will build the Larkfield Clinic staff appointment table with real table markup, tabular numbers, a sticky header and a sticky first column inside a labelled, keyboard-focusable scroll area, so it keeps its table semantics from a desktop monitor down to a 360 pixel phone.
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