← All experiments
Select theme appearance

Sparklines

This is an inline sparkline so it's base height is 1em.

Explanation

First up. Credits go to Quiet UI: Sparkline. Awesome lib!

Let's get into how to generate the SVG. We will need:

  • A Data Array of numbers: [5, 10, 8, 12, 7, 14, 6, 18, 10, 20]
  • A stroke width

Calculating the viewBox

The viewbox is calculated based on the data. The x-Max is the amount of values - 1. The y-Max is the highest value + stroke width. viewBox"0 0 (data.length - 1) (Math.max(...data) + strokeWidth)"

Calculating the paths

In order to calculate the path, we'll loop through the data points and draw points from one the the next. The y values need to be inverted, so we do viewBoxY - value.

`(index === 0 ? 'M' : 'L') (index) (viewBoxY - value)`

The gradient path extends this path, but adds two lines to the bottom corners and closes the path.

`(path)  L (viewBoxX) (viewBoxY) L 0 (viewBoxY) Z`

Finalising it

The line path needs the attribute `vector-effect="non-scaling-stroke"` so it keeps its stroke width.

The gradient is a simple fade to 100% transparency.

And the rest is styling and defaults to simplify it.

Pro Tip: inspect the element :)