Skip to content

Instantly share code, notes, and snippets.

@josephrocca
Last active March 16, 2021 17:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josephrocca/f5ae5ed019bf76deb4ae9bd439c1f3f9 to your computer and use it in GitHub Desktop.
Save josephrocca/f5ae5ed019bf76deb4ae9bd439c1f3f9 to your computer and use it in GitHub Desktop.
Simple sparklines with HTML5 canvas
function createSparkline(values, width=200, height=80, color='rgb(120,120,120)', maxValue) {
maxValue = maxValue || Math.max(...values);
values = values.map(v => (v/maxValue)); //normalise
let canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext('2d');
ctx.fillStyle = color;
ctx.moveTo(canvas.width, canvas.height);
ctx.lineTo(0, canvas.height);
for(let i = 0; i < values.length; i++) {
ctx.lineTo(canvas.width*i/(values.length-1), (1-values[i])*canvas.height); // 1-values because y axis is flipped
}
// `+1`s here are needed to prevent intersection with existing path which messes with filling:
ctx.lineTo(canvas.width, canvas.height+1);
ctx.lineTo(0, canvas.height+1);
ctx.closePath();
ctx.fill();
return canvas;
}
// usage:
// let spark = createSparkline([1,2,3,5,4,5,6,4,5,7,4,3,3])
// document.body.appendChild(spark);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment