Creating Animation Charts With HTML5 and JavaScript

Introduction

Hypertext Markup Language 5 (HTML5) is the latest version of the Hypertext Markup Language developed by the World Wide Web Consortium (W3C) used for structuring and presenting content for the World Wide Web. All popular browsers such as Google Chrome, Mozilla Firefox, Microsoft Internet Explorer and Opera supports HTML5. HTML5 provides support for document editing, drag and drop, audio and video playback, 2D graphics and browser history management.

JavaScript is a programming language used to create websites and make the pages interactive. JavaScript interacts with the HTML source code that enables web authors to spice up their websites with the dynamic content. JavaScript is an open language, which means that anyone can use it without purchasing a license.

Introducing the HTML5 Canvas API

The HTML5 Canvas API gives developers the ability to dynamically generate and manipulate graphics directly in the browser.

The most happening tag in HTML5 is the <canvas> tag. By simply specifying the area of a canvas, the browser creates the container accordingly. For example, to draw a canvas of the size 600 pixels wide and 400 pixels tall we can write the statement as:

  1. <canvas id="newcanvas" height="400" width="600"> </canvas>  

Although not all browsers support the <canvas> element, we are provided with alternative text for such browsers that place it between the opening and closing tags, as shown below:

  1. <canvas id="newcanvas" height="400" width="600"> Your browser does not support HTML5 Canvas </canvas>  

Browsers such as Mozilla FireFox, Google Chrome, iOS Safari, Opera, Internet Explorer 9 and Android support the <canvas> tag.

Canvas 2D Context Drawing basics

The canvas 2D is a two dimensional grid. The coordinates (0,0) of the canvas 2D is at the upper-left corner of the canvas. The value of the X-axis increases towards the right edge of the canvas and the value of the Y-axis increases towards the bottom edge of the canvas.

two dimensional canvas

Paths

A Path is just like drawing with a pencil. A path can be a sequence of one or more sub-paths where every new path begins with the beginPath() method. A sub-path can be a sequence of two or more paths connected by a line and where every new sub-path begins with the moveTo() method. We can connect a new point with a straight line by calling the lineTo() method after defining the starting point of a sub-path with the moveTo() method. The more we call the moveTo() and lineTo() methods, the bigger the path we will get.

Rectangle

Similarly we can draw a rectangle using one of 4 methods:

  • fillStyle(): The fillStyle property can be a pattern or a CSS color. The solid black color is the default fillStyle property.

  • strokeStyle(): This property sets or returns the style used by the strokes (lines) on shapes.

  • fillRect(x,y,width,height): The fillRect() method has the 4 parameters x, y, width and height used to draw the rectangle where x and y are the coordinates and the width and height are in pixels.

  • strokeRect(x,y,width,height): This method draws the outline of the rectangle without filling it in.

Here is a small demo to create a rectangle as shown below:

  1. <script>  
  2.   var canvas = document.getElementById('myCanvas');  
  3.   var context = canvas.getContext('2d');  
  4.   context.beginPath();  
  5.   context.rect(188, 50, 200, 100);  
  6.   context.fillStyle = 'yellow';  
  7.   context.fill();  
  8.   context.lineWidth = 7;  
  9.   context.strokeStyle = 'black';  
  10.   context.stroke();  
  11. </script>  

demo rectangle

Animating Bar Charts using HTML5

HTML5 can be used to draw simple or complex shapes and can also create graphs and charts. This article shows how to create a chart on a Canvas and how to animate it.

For visualizing data, bar charts are a popular tool. We will create a Bar Chart using HTML5 that will automatically position and draw itself from an array of data and we will use JavaScript for animating the chart.

I am using Visual Studio 2015 Preview, you can use any HTML5 editor.

Step 1

Open Visual Studio 2015 Preview

File -> New -> Project

Create a new ASP.NET Web Application and name it "HTML5CanvasandJavaScript" and save it at your preferred location.

create application template

And select Empty project template.

empty template

Step 2

Now add a new HTML page named "HTML5Canvas.html" and add the following Canvas markup to the <body> section as shown below:

body section

Step 3

Using the following data defined in an array, we will be able to draw the chart. Here the data represented in an array represents the marks obtained by different students on the basis of their roll number.

studentdata array

Step 4

Our next step is to use JavaScript to access and draw on the element, so let's go ahead and define the function BarChartAnimation() that draws the chart.

bar chart animation

Now first we retrieve the Canvas element by its ID from the Document Object Model (DOM) and create a two-dimensional rendering context if the element is found in the DOM. In the 2D rendering context we can draw nearly everything on the canvas. Once we have the drawing context, we can start to draw stuff.

Step 5

Let us first configure the BarchartSettings() function and begin to set some margins and drawing area. The total number of bars to be drawn and the width of each bar and data from the array to determine the maximum value of the graph to be plotted is calculated. See the following:

draw rectangle

Step 6

Now create a new function drawAxisLabelsandMarkers() that contains many calls to the functions drawXYAxis() and drawtheMarkers().

The function drawXYAxis() draws the X axis and Y axis lines depending on the parameters ed to it.

draw X&Y axis

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

The function drawtheMarkers() uses a simple for loop to add labels to the Y-axis as shown below:

y axis

For the X-axis we will use the data array defined to mark the labels as shown below:

x axis

Step 7

Now let us add titles to the X-axis and Y-axis. For adding a title to the Y-axis, rotate the context to add the title vertically as shown below:

y axis title

x axis title

As of now we are now ready with the basic structure of our application. If you run the application now, you will be able to see that the drawing surface contains the X-axis and Y-axis along with some markers.


Step 8

Now let's move further and plot the array data on the chart using animations. Since a canvas does not support animations we will be using JavaScript to animate the chart.

"Animations are all about timing!"

The following code iterates through all the data elements and draws a bar for each one by calculating the height of the bar and the X and Y points. We can simply change the speed of the animation by simply changing the ctr and speed variables in the BarchartSettings() function.

draw animationchart

Step 9

Call the drawRectangle() functions with five parameters that help us to draw rectangles around the charts.

drawrectangle

As discussed above, the paths are used to draw any shape on the canvas and here we are using the beginPath() function that starts a path and we draw a rectangle of the dimension w * h, whereas the function closePath() ends the path and the function stroke() makes the rectangle visible.

We have also added a gradient to the rectangle to construct the colored gradient, we have added multiple gradient.addColorStop() calls where each call has a unique offset, in other words 0 and 1.

Step 10

Now run your application and you will observe the growing bar animations in your browser.

output barchart1

output chart2

output chart3

Summary

With this article we have learned how to create an animating bar chart on the HTML5 Canvas using the JavaScript that helped us to animate the chart. What you think, is working with a Canvas fun?

Up Next
    Ebook Download
    View all
    Learn
    View all