× Please, log in to give us a feedback. Click here to login

You must be logged to download. Click here to login


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to Create Charts in HTML 5 and JavaScript

Today we are going to learn the technique used in creating attractive Charts in Web Application using HTML5 and JavaScript.

HTML5 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 give 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.

The <canvas> 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 <canvas>, which is 600 pixels wide and 400 pixels tall.

<canvas id="bchart" height="400" width="600">
Your browser does not support HTML Canvas

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 <canvas> tags, as shown above.

The Canvas tag is supported in IE9, Firefox, Chrome, Safari, iOS Safari, Opera, Opera Mobile and Android. To use explorercanvas, just check if the current browser is Internet Explorer and include a script tag in your page to use explorercanvas

<!--[if IE]><script src="excanvas.js"></script><![endif]-->

The basic HTML Canvas API includes a 2D context which a programmer can use to 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 still work in progress and not supported in the browsers.

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.

The Grid

Figure 1: The Grid

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.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. 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 HTML

The HTML 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. Here we will see 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 HTML 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 <body> section.

Listing 1: Adding Canvas markup in the <body> section

<body onLoad="barChart();”>
<canvas id=”bchart” height=”400” width=”600”>
Your browser does not support HTML Canvas

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.

Listing 2: Sample data defined in an array

// chart sample data
Var arrVisitors = new Array();
arrVisitors[0] = “2007, 750”;
arrVisitors[1] = “2008, 425”;
arrVisitors[2] = “2009, 960”;
arrVisitors[3] = “2010, 700”;
arrVisitors[4] = “2011, 800”;
arrVisitors[5] = “2012, 975”;
arrVisitors[6] = “2013, 375”;
arrVisitors[7] = “2014, 775”;

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.

Listing 3: Defining the barChart constructor

// barchart constructor
Function barChart() {
Canvas = document.getElementById(‘bchart’);
If (canvas && canvas.getContext) {
Context = canvas.getContext(‘2d’);

We retrieve the Canvas element by its ID and then ensure that the 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 we have the drawing context, we can start to draw stuff. 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.

Listing 4: Defining the chart and bar values

// initialize the chart and bar values
Function chartSettings() {
// chart properties
cMargin = 25;
cSpace = 60;
cHeight = canvas.height - 2 * cMargin - cSpace;
cWidth = canvas.widht - 2 * cMargin - cSpace;
cMarginSpace = cMargin + cSpace;
cMarginHeight = cMargin + cHeight;
//bar properties
bMargin = 15;
totalBars = arrVisitors.length;
bWidth = (cWidth / totalBars) - bMargin;

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

Listing 5: Finding maximum value to plot on Chart

// find maximum value to plot on Chart
maxDataValue = 0;
for (var I =0 < totalBars; i++) {
var barVal = parseInt(arrVal[1]);
if (parseInt(barVal)>parseInt (maxDataValue))
maxDataValue = barVal;

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.

Listing 6: Defining the function drawAxisLabelMarkers()

// draw X and Y axis
Function drawAxis (x,.y,X,Y) {

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.

Listing 7: Adding labels to the X-Axis

// X Axis
Context.textAlign = ‘center’;
For(var I =0; I < totalBars; i++) {
Arrval = arrVisitors[i].split(“,”);
Name = arval [0];
markerXPos = cMarginSpace + bMargin
                 + (I * (bWidth + bMargin)) + (bWidth/2);
markerYPos = cMarginHeight + 10;
context.fillText(name, markerXPos, markerYPos, bWidht);

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.

Listing 8: Adding labels to the Y-Axis

// Add Y Axis title
Context.translate(cMargin + 10, cHeight / 2);
Context.rotate(Math.PI * -90 / 180);
Context.fillText(‘Visitors in Thousands’, 0, 0);
//AddX Axis Title
Context.fillText(‘Year Wise’, cmarginSpace) + (cWidth / 2), cMarginHeight + 30);

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.

Visitors Chart

Figure 2: Visitors Chart

Let’s move ahead and plot the data array on this chart using animation.

The Canvas element does not support animations; hence we will be making use of 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 been reached.

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 it is preferred 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.

The below displays 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.

Listing 9: Defining the function drawChartWithAnimation()

function drawChartWithAnimation() {
// Loop through the total bars and draw
For (var I =0; I < totalBars; i++) {
Var arrVal = arrVisitors [i].split(“,”);
bVal = parseInt(arrVal[1]);
bHt = 
(bVal * cHeight / maxDatavalue) / numctr * ctr;
bX = cMarginSpace + (I * (bWidth + bMargin)) + bMargin;
bY = cMarginHeight – bHt – 2;
drawRectangle(bX, bY bWidth, bHt, true);
//timeout runs and checks if bars have reached
// the desired height; if not, keep growing
If (ctr < numctr) {
Ctr = ctr + 1;

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

Listing 10: Calling the drawRectangle() helper function

Function drawRectangle(x, y, w, h, fill) {
Context.rect(x, y, w, h);

if (fill) {
var gradient = context.createLinearGradient(0, 0, 0, 300);
gradient.addColorStop(0, ‘green’);
gradient.addColorStop(1, ‘rgba(67,203,36,.15)’);
context.fillStyle = gradient;
context.strokeStyle = gradient;

As we know 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 observe how the bars grow with an animation.


Figure 3: Charts

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


We created an animated Bar Chart using the HTML Canvas. We also used JavaScript in order to achieve the outcome. Hope you enjoyed the learning.

Software Developer from India. I hold Master in Computer Applications Degree and is well versed with programming languages such as Java, .Net, C and C++ and possess good working knowledge on Mobile Platforms as well.

What did you think of this post?
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!

> More info about MrBool Credits
You must be logged to download.

Click here to login