HTML5 Recipes : Graphs using Canvas

In this recipe, we shall take a look at generating charts using the HTML5 Canvas API. In particular we shall be using a library RGraph, which makes internally uses the Canvas API and makes the entire process of generating charts a breeze. We shall assume that the user is familiar with Canvas basics and do read up earlier episodes of this series in case you need a refresher. Using the Canvas API for your charting requirements can have significant benefits since you are avoiding a lot of heavy duty server side processing and instead relying on the local browser doing all the hard work. It can also be useful in offline situations where if you have cached the data offline using local storage API, you can still slice and dice the information via charting that is solely dependent on the Canvas API. No server side connection and round trips needed just to render your data.

The RGraph library as the site suggests allows you to create Interactive javascript/HTML5 canvas graphs using the HTML5 canvas tag for all platforms. The library caters to charts of all types i.e. simple bar, pie charts to sophisticated ones like scatter and rose charts. The library is free for non-commercial use but requires a one-time fee in case of commercial applications. Please refer to the license for more details.

To get started with the RGraph library, download the latest version and expand the zip file to a particular folder on your machine. You will find several directories in the distribution and the main one that we need to pay attention to is thelibraries folder. This folder contains pieces of the RGraph library that have been nicely split up into individual functionalities. This way you do not have to import a single large JS file if you do not need all the features. At the minimum, you need the RGraph.common.core.js, which is the core library and depending on which chart type you wish to employ, you can import the other JS files individually. For e.g. if you need the bar chart, include a reference in your HTML file to RGraph.bar.js file. The documentation for the RGraph library is impressive and it contains enough examples to build fairly interactive charting applications.

Let us take a look at a simple example of generating a bar chart and pie chart using the RGraph library. This is the simplest usage that one can think of and the results are impressive. This is not to say that you cannot use the core Canvas API to generate charts but in case you prefer using quality libraries to do your task, the RGraph library is quite useful in that regard.

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0" />

<title>Graphs using Canvas</title>

<script src="rgraph/RGraph.common.core.js"></script>

<script src="rgraph/RGraph.bar.js"></script>

<script src="rgraph/RGraph.pie.js"></script>

<script>

window.onload = function ()

{

    var blogpostspermonthdata = [1,2,4,5,3,4,5,6,10,3,2,1];

    var barchart = new RGraph.Bar('barchartcanvas', blogpostspermonthdata);

    barchart.Set('chart.labels', ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']);

    barchart.Set('chart.title','Blog Posts per month');

    barchart.Draw();

    var browsersharedata = [20,10,40,30];

    var piechart = new RGraph.Pie('piechartcanvas', browsersharedata);

    piechart.Set('chart.labels', ['Safari', 'IE', 'Chrome', 'Firefox']);

    piechart.Set('chart.labels.sticks',true);

    piechart.Set('chart.title','Browser Share');

    piechart.Draw();

}

</script>

</head>

<body>

  <div id="canvas1">

  		<canvas id="barchartcanvas" width="400" height="300">Your browser does not have canvas support</canvas>

  </div>

  <div id="canvas2">

        <canvas id="piechartcanvas" width="400" height="300">Your browser does not have canvas support</canvas>

  </div>

</body>

</html>

Let us break the code down now:

  • We have defined two canvas drawing surfaces i.e. barchartcanvas and piechartcanvas that will host the bar graph and pie chart respectively.
  • Notice that we have imported 3 script files for the RGraph library, the core library and the barchart and piechart library respectively.
  • The bar graph that we plan to display contains the number of blog posts that have been written at a blog. There are 12 data points, one for each month. Remember that for the sake of demonstration, I have hard coded the values over here, but this could come from the Server side. Alternately, you could also have retrieved it from the local storage, in case you have fetched the data earlier and put it over there. Then we build the barchart object based on the RGraph library. We specify the canvas object and the data values as the two parameters. We set the labels and title and then simply call Draw().
  • The pie chart also follows a similar pattern. There are many more properties for each of the chart types and I suggest you refer to the documentation.

See it in action here.


HTML5 Canvas Recipes

  1. Getting Started with Canvas
  2. Rectangles
  3. Strokes and Fills
  4. Drawing Text
  5. Paths
  6. Circles and Arcs
  7. Images
  8. Graphs With Canvas

Back to HTML5 Series

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s