HTML5 and CSS3, Second Edition

(singke) #1

Tip 18


Tip 18. Graphing Statistics with RGraph


The canvas is great for drawing images, but the fact that we build objects on
the canvas using JavaScript means we can use this for data visualization as
well. Let’s use the canvas to create a simple graph.

There are lots of ways to draw graphs on a web page. In the past, developers
used Flash for graphs all the time, but that has the limitation of not working
on some mobile devices, like the iPad and iPhone. Some server-side solutions
work well, but those might be too processor-intensive if you’re working with
real-time data. A standards-based client-side solution like the canvas is a
great option as long as we’re careful to ensure it works in older browsers.
You’ve already seen how to draw squares, but drawing something complex
requires a lot more JavaScript. We need a graphing library to help. The RGraph
library makes it ridiculously simple to draw graphs using the HTML5 canvas.^3
It’s a pure JavaScript solution, though, so it won’t work for user agents that
don’t have JavaScript available; but then again, neither will the canvas. Here’s
the code for a simple bar graph:

html5_canvas/rgraph_bar_example.html
<canvaswidth="500"height="250"id="test">[no canvassupport]</canvas>

<scriptsrc="javascripts/RGraph.common.js"></script>
<scriptsrc="javascripts/RGraph.bar.js"></script>

<scripttype="text/javascript"charset="utf-8">
var bar = new RGraph.Bar('test', [50,25,15,10]);
bar.Set('chart.gutter',50);
bar.Set('chart.colors',['red']);
bar.Set('chart.title',"A bar graphof my favoritepies");
bar.Set('chart.labels',["Banana Creme","Pumpkin","Apple","Cherry"]);
bar.Draw();
</script>

All we have to do is create a couple of JavaScript arrays to hold the data, and
RGraph draws the graph on the canvas for us. Using this data, we get a graph
like in the following figure.


  1. http://www.rgraph.net/


Chapter 6. Drawing in the Browser • 120


Download from Wow! eBook <www.wowebook.com> report erratum • discuss

Free download pdf