Vanilla JavaScript Projects

Project 82, Content and data

SVG Charts Kit

Three chart types in about 150 lines of JavaScript. They are sharp at any size, readable by screen readers and weigh almost nothing compared to a chart library.

Main API
Inline SVG
Motion
stroke-dasharray
Dependencies
None
Your browser
Checking

Sales dashboard

Hover or tab through points and bars for tooltips. Toggle series in the legend. Press Shuffle to load new numbers.

Revenue by month

Sales by channel

Orders by weekday

Show the data as a table

How it works

  1. Scale data to pixelsEach chart maps values to a viewBox with two tiny functions, x(i) and y(v). The viewBox makes the chart scale to any width.
  2. Draw with pathsThe line is one path of M and L commands. Bars are rects. The donut uses circles with stroke-dasharray slices.
  3. Tooltips for mouse and keyboardEvery point is a focusable group with a label. Hover or focus shows the same tooltip, and screen readers read the label.
const x = (i) => pad + i * (width - pad * 2) / (values.length - 1);
const y = (v) => height - pad - (v / max) * (height - pad * 2);
const d = values.map((v, i) => (i ? "L" : "M") + x(i) + " " + y(v)).join(" ");
svg.innerHTML = `<path d="${d}" fill="none" stroke="#7C3AED" stroke-width="3"/>`;

// donut slice
const len = (value / total) * 2 * Math.PI * r;
circle.setAttribute("stroke-dasharray", `${len} ${circumference - len}`);