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
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
Your browser does not support HTML5 Canvas
As of this writing, some browsers do not support the
The Canvas tag is supported in IE9, Firefox, Chrome, Safari, iOS Safari, Opera, Opera Mobile and Android. To use the 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
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.
Create a file named “canvaschart.html” and add the following Canvas markup in the
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.
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.
The following piece of code then extracts data from the array to find the maximum value to plot on the graph
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.
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
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.
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.
So far, so good! Let’s move ahead and plot the array data on this chart using animation.
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!”
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 .
With the dimensions calculated above, call the drawRectangle() helper function, which draws a rectangle around the charts.
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
Go ahead and try changing the values in the array and you will observe that the chart updates automatically.
Download the source code or see a Live Demo
References: HTML5 Cookbook http://bit.ly/KILcAg