sparklines
by hiddenloop
HTML
<div class="box">
<p class="sparkline">
<canvas width="200" height="44"></canvas>glucose <i class="recent"></i>
</p>
</div>
CSS
html,
body {
font: normal 200 12px/1.6"Ubuntu", sans-serif;
color: #555;
background-color: rgb(245, 250, 255);
}
.sparkline {
margin: 0 0 5px 0;
text-transform: uppercase;
}
.box {
box-sizing: border-box;
width: 320px;
padding: 24px;
background-color: white;
display: inline-block;
margin: 10px 10px 0 0;
}
.sparkline canvas {
vertical-align: bottom;
display: inline-block;
margin: 0;
padding: 0 0.5em;
width: 100px;
height: 22px;
}
i {
color: rgb(255, 0, 0);
font-style: normal;
}
JavaScript
// based on: https://raw.githubusercontent.com/adactio/Canvas-Sparkline/master/sparkline.js
// TODO:
// * units
// * min/max/avg reporting
// * interval averages
// * variance
// * reactjs component
// * @data on canvas
var sparkline = function(id, data, normal, startpoint, endpoint, color, style) {
if (window.HTMLCanvasElement) {
var sparkline = (typeof(id) === 'string') ? document.getElementById(id) : id;
var recent = sparkline.getElementsByClassName('recent')[0];
recent.innerHTML = data[data.length - 1];
var ctx = sparkline.getElementsByTagName('canvas')[0].getContext('2d');
var colour = (colour ? colour : 'rgba(0,0,0,0.5)');
var style = (style == 'bar' ? 'bar' : 'line');
var height = ctx.canvas.height - 8; // padding
var width = ctx.canvas.width - 8; // padding
var total = data.length;
var max = Math.max.apply(Math, data);
var xstep = width / total;
var ystep = max / height;
var x = 0;
var y = height - data[0] / ystep;
var i;
ctx.translate(3, 3);
if (normal && normal.length == 2) {
ctx.beginPath();
ctx.fillStyle = 'rgba(210,220,210,0.5)';
ctx.fillRect(0, height - (normal[1] / ystep) | 0, width, (normal[1] - normal[0]) / ystep | 0);
}
if (startpoint && style == 'line') {
ctx.beginPath();
ctx.fillStyle = 'rgba(255,0,0,0.5)';
ctx.fillRect(x - 3, y - 3, 6, 6);
}
ctx.beginPath();
ctx.strokeStyle = colour;
ctx.lineWidth = 2;
ctx.moveTo(x, y);
for (i = 1; i < total; i = i + 1) {
x = x + xstep;
y = height - data[i] / ystep + 1;
if (style == 'bar') {
ctx.moveTo(x, height);
}
ctx.lineTo(x, y);
}
ctx.stroke();
if (endpoint && style == 'line') {
ctx.beginPath();
ctx.fillStyle = 'rgba(255,0,0,0.5)';
ctx.fillRect(x - 3, y - 3, 6, 6);
}
}
};
// fake some data
var data_faker = function(max, length) {
var array = [];
for (length; length--;) {
...