Javascript HTML/CSS Charts

by Naneau

Charts are hot nowadays. There are plenty of implementations for the web 2.0 world out there. Most of them are either written in flash, or use some combination of the canvas tag and SVG for rendering. When I was experimenting with plotkit the other day it occurred to me that all it outputs is rectangular shapes, it’s bars.

Now, rectangular things is something HTML is very good at defining. So I thought, why not build a simple charting engine that just uses HTML and some CSS to create good looking charts. Using the native rendering engine of a browser, while a lot less powerful than both Flash and canvas/SVG, would be widely supported. As today was quite rainy and I had some time to spare, and decided to give it a try.

The result is, well, I am kind of proud of it. I based it on prototype, as I am familiar with it. It was also a nice opportunity for me to test the new morphing effects of script.aculo.us. They aren’t completely necessary of course, but they do make the charts look nicer and more dynamic.

The resulting class can be used like this, with prototype AJAX calls:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var chart = new CssChart('chart');
//create the chart

new Ajax.Request(url_root + 'csscharts/data',
{
    onSuccess: function(rq){
        chart.readJson(rq.responseText.evalJSON(), 'data', 'label', 'value');
        //feed json data to the chart
        //assuming the root element is 'data',
        //labels are called 'label', and values 'value'
       
        chart.build();
        //build it
       
    }.bind(chart)
});
//request data and make chart read it

The readJson method can be used to create charts using nothing but JSON data. As of yet it is also the only way to create charts. You can of course create objects on the fly and feed them to the method.