javascript 31 lines · 8 steps

Rendering a sparkline as SVG

A pure function maps a numeric series onto SVG path coordinates to draw a compact inline chart.

Explained by highlit
1function sparkline(values, { width = 200, height = 40, stroke = '#2563eb', fill = 'rgba(37,99,235,0.12)' } = {}) {
2 if (!Array.isArray(values) || values.length < 2) {
3 throw new RangeError('sparkline requires at least two data points');
4 }
5 
6 const min = Math.min(...values);
7 const max = Math.max(...values);
8 const range = max - min || 1;
9 const pad = 2;
10 const innerW = width - pad * 2;
11 const innerH = height - pad * 2;
12 const stepX = innerW / (values.length - 1);
13 
14 const points = values.map((value, i) => {
15 const x = pad + i * stepX;
16 const y = pad + innerH - ((value - min) / range) * innerH;
17 return [Number(x.toFixed(2)), Number(y.toFixed(2))];
18 });
19 
20 const line = points.map(([x, y], i) => `${i === 0 ? 'M' : 'L'}${x},${y}`).join(' ');
21 const area = `${line} L${points[points.length - 1][0]},${height - pad} L${points[0][0]},${height - pad} Z`;
22 const [lastX, lastY] = points[points.length - 1];
23 
24 return `<svg viewBox="0 0 ${width} ${height}" width="${width}" height="${height}" `
25 + `role="img" aria-label="sparkline from ${min} to ${max}">`
26 + `<path d="${area}" fill="${fill}" stroke="none" />`
27 + `<path d="${line}" fill="none" stroke="${stroke}" stroke-width="1.5" `
28 + `stroke-linejoin="round" stroke-linecap="round" />`
29 + `<circle cx="${lastX}" cy="${lastY}" r="2.5" fill="${stroke}" />`
30 + `</svg>`;
31}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Mapping data to pixels means normalizing values into a fixed range and flipping the y-axis for screen coordinates.
  2. 2Building SVG by hand is just assembling a path string plus attributes, no library required.
  3. 3Guarding inputs and reserving padding upfront keeps rendering math simple and safe.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Rendering a sparkline as SVG — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code