A sparkline on canvas
A small line that shows the latency trend. Scale the values to the canvas height and draw the polyline.
Write drawSparkline(canvas, values). Draw a polyline from left to right with lineWidth = 2, leaving a margin of PAD pixels on all four sides:
- x of point i: PAD + i * (width - 2 * PAD) / (values.length - 1);
- y: the minimum sits at the bottom (height - PAD) and the maximum at the top (PAD). Remember that on canvas y grows downwards.
If every value is the same, draw a horizontal line through the middle instead of dividing by zero. Clear the canvas before drawing.
SERIES holds ten example latencies in milliseconds.
Challenges 0/4
- Draws something on the canvas
- The highest point (12 ms) reaches the top
- The lowest point (3 ms) sits at the bottom left
- With equal values it draws a line through the middle
function drawSparkline(canvas, values) {
const ctx = canvas.getContext('2d');
const { width: w, height: h } = canvas;
ctx.clearRect(0, 0, w, h);
// 1. min and max of values
// 2. map each value to (x, y) inside the PAD margin
// 3. ctx.beginPath(), moveTo / lineTo, ctx.stroke()
}
drawSparkline(document.getElementById('spark'), SERIES);Go deeper: the MDN reference →
This in production, with your data? Let's talk for 15 minutes →