How to Build a Graph using HTML5 Canvas Tag and JSON

Some web projects require data to be expressed as a visual graph. While there are libraries that can do this, it's not a bad idea to understand how it can be done using the facilities available to HTML5.

The CANVAS tag which is a part of the HTML5 lexicon provides the means to draw some pretty complex things using vectors. Vectors are points along a line, and lines are what we'll use to draw our graphs. Now we need some data to graph.

Data for charting generally can be expressed as XML or JSON; personally I like JSON better as it's more readily consumable by javascript whereas XML has to be converted into javascript for consumption by a front-end. (Note: doing this with XML isn't that much more difficult, it's just an extra step that can easily be eliminated through efficiency depending on how the data you'll consume is being produced.) This example will plot a single line representing the some imaginary data metric.

Clicking the button will call the plotGraph function (shown in the code sample below) passing the id of the CANVAS tag and a data structure containing our graphing plots.

As an aside, I'm passing these arguments as a named array ("hash" if you prefer the lingua-franca of PERL, or "associative array" if you just love words). Speaking of PERL, this is a trick I learned from programming in PERL; programmers are initially taught to pass arguments as a simple array. This isn't a problem until the list of arguments becomes long...and/or you want to change the order you pass the arguments. Because an array is ordered you have to be careful to change all of the places calling your function so the order they pass matches the order the function wants to receive them in. If there are many callers, that's a lot of places to change and re-test. However, by using a hash (named array), the order doesn't matter...instead the function is getting values by looking at their associated keys. So if you look at the plotGraph function below, args['foo'] would get the value passed as the counterpart of 'foo', such as {'foo' : 'this is the value of foo'}. JavaScript frameworks have adopted this type of arguments passing as standard practice--and for good reason, it's a great idea!

Thanks for your time, and as always, feedback is appreciated. (You can contact me via the "contact the author" link.) Be sure to check out some of my other examples and give our sponsors consideration--their support helps us keep this site running. Best wishes!