Skip to content

Instantly share code, notes, and snippets.

@foxt
Created February 28, 2020 12:34
Show Gist options
  • Select an option

  • Save foxt/7e43b37ec029960bc0f34e03bced46d9 to your computer and use it in GitHub Desktop.

Select an option

Save foxt/7e43b37ec029960bc0f34e03bced46d9 to your computer and use it in GitHub Desktop.
Sparkline custom element
// Sparky v1.0
// theLMGN - https://github.com/thelmgn
// Example: <canvas is="spark-line" width="300" height="200" data="5,3,6,9,10,5" color="#52ACD4"></canvas>
class Sparky extends HTMLCanvasElement {
constructor() {
super();
var observer = new MutationObserver(function(mutations) {
try {
return this.render()
} catch(e) {
console.error("Sparky:",this,"Failed to update!",e)
}
}.bind(this));
observer.observe(this, {attributes: true});
}
render() {
try {
var ctx = this.ctx
var color = this.getAttribute("color")
if (!ctx) {return console.error("Sparky: ",this,"no ctx!")}
ctx.clearRect(0,0,this.width,this.height)
try {
var d = JSON.parse("["+this.getAttribute("data")+"]")
} catch(e) {}
if (!d) {return console.error("Sparky: ",this,"invalid data!")}
if (d.length < 2) {return console.error("Sparky: ",this,"not enough data!")}
if (!color || color.length != 7 || !color.startsWith("#") || isNaN(parseInt(color.replace("#",""),16))) {return console.error("Sparky: ",this,"color is missing or not valid")}
var xPPP = this.width / (d.length - 1)
var yMin = Math.min(...d)
var yMax = Math.max(...d)
var yRng = yMax - yMin
var yPPP = (this.height / yRng)
var i = 0
//var lastPos = [500, 475]
ctx.beginPath();
ctx.moveTo(0,this.height - (d[0] - yMin) * yPPP)
var pos = []
for (var i in d) {
pos = [parseInt(i) * xPPP, this.height - ((d[i] - yMin) * yPPP)]
ctx.lineTo(...pos)
}
ctx.lineTo(this.width + 5,pos[1])
ctx.lineTo(this.width + 5,this.height + 5)
ctx.lineTo(-5,this.height + 5)
ctx.lineTo(-5,(d[0] - yMin) * yPPP)
ctx.lineTo(0,(d[0] - yMin) * yPPP)
var grd = ctx.createLinearGradient(0,0,0,this.height);
grd.addColorStop(0,color+ "AA");
grd.addColorStop(1,color + "00");
ctx.strokeStyle = color
ctx.stroke();
ctx.fillStyle = grd
ctx.fill()
} catch(e) {
console.error("Sparky:",this,"Failed to render!",e)
}
}
connectedCallback() {
this.ctx = this.getContext("2d")
this.render()
}
disconnectedCallback() {
delete this.ctx
this.remove()
delete this //delet this
}
}
customElements.define('spark-line', Sparky, { extends: 'canvas' });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment