Last active
March 16, 2021 17:53
-
-
Save josephrocca/f5ae5ed019bf76deb4ae9bd439c1f3f9 to your computer and use it in GitHub Desktop.
Simple sparklines with HTML5 canvas
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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