Giacomo Balli profile picture
Giacomo Balli
The Mobile Guy

Over two decades of experience at your service.
I help business owners make better decisions.

Let's Chat LinkedIn

Create graphs with HTML5 JavaScript and CSS3

The big deal of HTML5 is that it brings A LOT of power to modern browsers; it's isn't just the addition of semantic tags or declaration updates.
One of the most astonishing additions is being able to easily replace Flash.
Take for example data visualization. Before, you could only use Flash to automatically generate graphs related to data. Flash is bulky, and take long(er) time to update. Not to mention its production time.
Alternatives used to be <img> (image element) or <svg> (scalable vector graphics)
<img>: This obviously is nothing new (although still an alternative to Flash). In a few very specific cases, this could still be the best route.
<svg>: Much more dynamic capabilities but also complicated to implement
<canvas>: Awesomeness. Programmatically create multiple kinds of graphs with different styling.
Take the following snippet:
for ( var i = 0; i < data.length; i++ ) {
    var dx = (colW * i) + padding;
    var dh = canvas.height * (data[i]/10);
    var dy = canvas.height - (dataHeight-1);

context.fillRect( dx, dy, colW-2*padding, dh ); context.strokeRect( dx, dy, colW-2*padding, dh ); }
... that is all it takes to create the bar graph below.
Different graph examples:
for ( var i = 0; i < data.length; i++ ) {
    context.arc(data[i].x, data.y, 10, 0, Math.PI*2, false);
Doubt it gets any easier!
Check out more in depth info here.

#canvas, #graphs, #html5
Published: Sat, Oct 6 2012 @ 11:19:07
Back to Blog