Sparklines.js

Dynamic sparklines for live output using pure JS + Canvas

by khrome

HTML

<div class="spark_container">
    <span id="spark" class="sparklines"></span>
</div>

JavaScript

function SparkLines(options){ //pure js, no requirements
    this.options = options;
    if(!this.options.height) this.options.height = 40;
    if(!this.options.width) this.options.width = 200;
    if(!this.options.sparkWidth) this.options.sparkWidth = 4;
    if(!this.options.sparkGap) this.options.sparkGap = 1;
    if(!this.options.cieling) this.options.cieling = 100;
    if(!this.options.floor) this.options.floor = 1;
    this.options.range = this.options.cieling - this.options.floor;
    if(typeof(this.options.element)=='string') this.options.element = document.getElementById(this.options.element);
    this.canvas = document.createElement('canvas');
    this.canvas.width = this.options.width;
    this.canvas.height = this.options.height;
    this.options.element.appendChild(this.canvas);
    this.context = this.canvas.getContext('2d');
    this.windowOccludeWidth = this.options.sparkGap + this.options.sparkWidth;
    this.translateWindowWidth = this.options.width - this.windowOccludeWidth;
    this.shift = function(value){
        this.pixels = this.context.getImageData(this.windowOccludeWidth,0, this.translateWindowWidth, this.options.height);
        this.context.putImageData(this.pixels, 0, 0);
    },
    this.addValue = function(value){
        var height = (value / this.options.range) * this.options.height;
        this.shift();
        this.context.clearRect(this.translateWindowWidth, 0, this.options.sparkWidth, this.options.height);
        this.context.fillRect(this.translateWindowWidth, this.options.height - height, this.options.sparkWidth, height);
    }
}
var sparks = new SparkLines({
    element : 'spark',
    cieling : 100,
    floor : 0
});

setInterval(function(){
    sparks.addValue(Math.random()*100);
}, 1);