DotNetCurry Logo

Bring Your Charts to Life with HTML5 Canvas and JavaScript

Posted by: Suprotim Agarwal , on 10/17/2012, in Category HTML5 & JavaScript
Views: 80362
Abstract: This article demonstrates how to create an animated Bar Chart on the HTML5 Canvas using a little bit of JavaScript and a little bit of imagination

HTML5 is the new lingua franca for the Web. It is a promising and evolving technology under the Open Web Standard and has been written primarily to develop better, more efficient web applications in the era of cloud computing and mobile devices. HTML5 kicks off a whole new era for web developers, by moving HTML from being a relatively simple markup language to providing a host of new markup and rich API’s for the construction of web applications.

One such rich API is the Canvas API.

Introducing the HTML5 Canvas API

The HTML5 Canvas API is a set of client-side functions, which gives developers the ability to dynamically generate and manipulate graphics directly in the browser, without resorting to server-side libraries, Flash, or other plugins. The Canvas API gives you a fine level of control over the individual pixels on your page. It is like a blank slate on which we use JavaScript to draw and animate objects.

dncmag
This article is published from the DNC Magazine – A Free High Quality Digital Magazine for .NET professionals published once every two months.

This month's edition features hot topics like ASP.NET MVC4, SignalR, Knockout.js, jsRender, TDD, Visual Studio ALM, HTML5, SharePoint, Windows Azure and Metro Applications amongst others. Not to mention, a freewheeling interview with Ayende Rahien, the man behind RavenDB.

Download this Free Magazine Here

“To get the most out of the Canvas element, you need CSS3 and JavaScript. HTML5 and CSS3 Are Still Works in Progress”

The tag is one of the most happening tags in HTML5. To draw a Canvas, simply specify how large you want the canvas area to be, and the browser creates the container accordingly. For example, here’s how to draw a , which is 600 pixels wide and 400 pixels tall.

Your browser does not support HTML5 Canvas

As of this writing, some browsers do not support the element. Hence we have to provide alternative content for such browsers. This alternative content is provided by placing it in between the opening and closing tags, as shown above.

The Canvas tag is supported in IE9, Firefox, Chrome, Safari, iOS Safari, Opera, Opera Mobile and Android. To use the tag in IE 6, 7, or 8, download the opensource ExplorerCanvas project from http://code.google.com/p/explorercanvas/. To use explorercanvas, just check if the current browser is Internet Explorer and include a script tag in your page to use explorercanvas

Alternatively also explore the Modernizr library.

The basic HTML5 Canvas API includes a 2D context using which a programmer can draw various shapes, images and render text directly onto the Canvas. Calling getContext(‘2d’) returns the CanvasRenderingContext2D object that you can use to draw two-dimensional graphics into the canvas.

3D contexts are defined by passing in contexts such as webgl, experimental-webgl, and others. This is work in progress.

Canvas 2D Context Drawing basics

The canvas’s 2D context is a grid. The coordinate (0, 0) is at the upper-left corner of the canvas. When you draw on this grid, you specify the starting X and Y coordinates and the width and height. Moving to the right will increase the x value, and moving downwards will increase the y value

CanvasAxisArea

Paths are used to draw lines on a canvas and fill the areas enclosed by those lines. A path can be defined as a sequence of one or more sub-paths and you begin a new path with the beginPath() method. A sub-path can be defined as a sequence of two or more points connected by a line and you begin a new sub-path with the moveTo() method. Once you have defined the starting point of a sub-path with the moveTo() method, you can connect that point to a new point with a straight line by calling lineTo().

Similarly you can draw a rectangle using 4 different methods, one of which is the fillRect() method. If you do not want to fill the rectangle with any color, use strokeRect(). By default, the rectangle’s fill color is black but you can change it using the fillStyle() function. You can fill the rectangle with either a solid color, a gradient, or even a pattern using the strokeStyle() function.

Now that we have explored some basics of the Canvas element, let’s see it in action.

Animating Bar Charts using HTML5

As mentioned earlier, the HTML5 canvas is revolutionizing graphics and visualizations on the Web and we can use it to create simple or complex shapes or even create graphs and charts. In this article, I will show you how to draw a Bar Chart on the Canvas and then animate it.

Bar charts are a popular tool for visualizing data. We will create a Bar Chart using HTML5 Canvas that can automatically position and draw itself from an array of data. Since Canvas does not support Animations, we will use JavaScript to animate the chart.

Create a file named “canvaschart.html” and add the following Canvas markup in the section

CanvasBody

We have named the Canvas with an id attribute ‘bChart’ which will be used to link the JavaScript definition to this element.

We have declared the Canvas dimensions (height and width) right inside the markup. Although you should use CSS to control the dimensions of your HTML controls, unfortunately here you can’t do that. If you do, the contents get distorted. So you are forced to decide on your canvas dimensions when you declare it.

We will draw the chart from a set of sample data defined in an array. The data represents the traffic of a site (in thousands) for a given year.

GraphArray

After you place the Canvas element in a document, your next step is to use JavaScript to access and draw on the element. Let’s go ahead and define the barChart constructor that draws the chart

BarConstructor

We retrieve the Canvas element by its ID and then ensure if that element is available within the DOM. If it is available, create a two-dimensional rendering context. The 2d rendering context is the coolest part of the Canvas on which you can draw almost everything. The Canvas element acts as a wrapper around the 2d rendering context and provides all the methods and properties to draw on the context and manipulate it.

Once you have the drawing context, we can start to draw stuff. Exciting times!

Let’s first configure some settings of the chart in the chartSettings() function. Start by setting some margin and drawing area. Then calculate the total bars to be drawn of the chart and determine the width of each bar, as shown below.

ChartSettings

The following piece of code then extracts data from the array to find the maximum value to plot on the graph

ChartMaxVal

Define a new function drawAxisLabelMarkers() that contains call to functions drawAxis() and drawMarkers(). drawAxis() draws the X and Y axis lines depending on the parameters passed to it.

CanvasDrawAxis

For the X-axis, we will draw a line from the lower left to right whereas for the Y-axis, we will draw a line from the lower left to upper left.

The drawMarkers() function uses a simple loop to add labels to the Y-axis. For the X-axis, we will use the data array to mark labels, as shown below

CanvasXAxis

Finally add the titles to the X and Y-axis. While adding a title to the Y-axis, rotate the context to add a title vertically. Once done, restore the context.

CanvasYAxis

We are now ready with the barebones of our application. If you view the application in a browser, you will see that the drawing surface contains the X and Y-axis along with some markers.

CanvasAxis

So far, so good! Let’s move ahead and plot the array data on this chart using animation.

The Canvas element does not support animations. So how are we supposed to animate the charts? You guessed it right! The answer is using JavaScript.

To achieve an animation effect with bars, we need a way to loop through the bars and set a timeout to grow the bars in steps. Once the function starts drawing the bar dimensions, it will regularly check if the step was the last step in the animation. If not, repeatedly run after a certain number of milliseconds have elapsed, till the last step in the animation has reached.

“Animations are all about timing!”

You set a timeout using the window’s setTimeout() method, which accepts two arguments: the function to execute and the amount of time (in milliseconds) to wait before attempting to execute the code. We can use setInterval() too, but I prefer using setTimeout() over setInterval() for the reason that JavaScript dishonors call to setInterval() when the last task added to the UI queue is still in there. This leads to jerky animations.

Note: If you are dealing with heavy WebGL based graphics, explore the requestAnimationFrame method instead of setTimeout. It works similar to the setTimeOut and you can request for an animation callback inside your function. The advantage with requestAnimationFrame is that webbrowsers can decide on the optimal fps of the animation and can reduce it for scenarios where a user moves to a different tab or minimizes the screen.

Shown here is the code that loops through all the data elements, and draws a bar for each one in steps by calculating the bar height and the X & Y points. To change the speed of the animation, all you need to do is change the ctr and speed variables in the chartSettings() function .

ChartWithAnimation

With the dimensions calculated above, call the drawRectangle() helper function, which draws a rectangle around the charts.

DrawRectangle

As we had discussed in the beginning of this article, paths are used to draw any shape on the canvas. A path is simply a list of points, and lines to be drawn between those points. Here the beginPath() function call starts a path and we draw a rectangle of the dimension w * h. The closePath() function call ends the path and stroke() makes the rectangle visible.

We have also added a gradient to the rectangles. In order to construct this colored gradient, we have added multiple gradient.addColorStop() calls. Each of them has a unique offset - i.e. 0 and 1. Note that you do not need to use only 0 and 1; you can use any two partial values like 0.25 to 0.75.

Run the application and you observe how the bars grow with an animation

ChartFinal

Go ahead and try changing the values in the array and you will observe that the chart updates automatically.

If you plan to do some advanced graphs using the Canvas, I would suggest exploring the RGraph tool that makes it ridiculously simple to draw graphs using the HTML5 canvas and JavaScript.

Working with the Canvas is so much fun. We just created an animated Bar Chart on the HTML5 Canvas using a little bit of JavaScript and a little bit of imagination! With this sample application, we have scratched the surface of the canvas API and there’s much more to come. Stay tuned!

Download the source code or see a Live Demo

References: HTML5 Cookbook http://bit.ly/KILcAg

Was this article worth reading? Share it with fellow developers too. Thanks!
Share on Google+
Further Reading - Articles You May Like!
Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Paolo on Thursday, October 18, 2012 12:10 AM
Although the rGraph chart is not free for commerical use, but you have written a good article. keep it up
Comment posted by Richard on Friday, October 19, 2012 3:12 AM
> Although the RGraph chart is not free

It's not - but the prices have just come down - so it's a great time to look at it! </plug>
Comment posted by Matthew Kane on Thursday, October 25, 2012 6:38 AM
Suprotim, great tutorial. I modified your sample to make a Pie chart and it worked well.
Comment posted by Mahesh Sabnis on Friday, December 14, 2012 5:31 AM
Hi,
  This is really Great article on HTML 5.

Thanks
Mahesh S.
Comment posted by SC Vinod on Monday, January 21, 2013 11:14 PM
Excellent article mate.
Comment posted by Doniv on Tuesday, January 22, 2013 4:42 AM
Hi, Can you tell me how do I remove the animation from the code? Also how can I get the full height of each of the bars in the code?
Comment posted by Feroz Ahmed on Tuesday, May 14, 2013 5:37 AM
post code for scatter chart..
Comment posted by UGUR CAKMAkki on Sunday, February 8, 2015 1:12 PM
I WANT TO GET DATA FROM TEXT FILE.. YOU GET DATA FROM IN CODE.
IF YOU CAN DO IT.. IT IS VERY GOOD..
Comment posted by lex on Monday, May 25, 2015 1:09 PM
http://mrbool.com/how-to-create-charts-in-html-5-and-javascript/26937