HTML5 | How to draw a Doughnut chart using ChartJS

Web Project

ChartJS is a wonderful javascript code that you can use in your project to create awesome charts quickly and quite easily. In this tutorial we will be learning to create a Doughnut chart using ChartJS. For this project we will need the following resource.

First thing first

Download ChartJS and jQuery from their website. If you have already download them then move to the next step.

Creating Project Folder

Create a project folder on your desktop or at a location of your choice. Name the project folder. For instance, I have named it doughnut. Inside the doughtnut folder create another folder called js. Next copy the ChartJS and jQuery javascript files into the js folder. Finally open this folder in your favourite text editor or IDE and create script.js file inside the js folder.

Create Index page

Now its time for us to create an index.html page inside the project folder.

Code

Alright then, time to write some code. Inside the index.html file create the basic structure of an html file and include the script.js, ChartJS and jQuery javascript files that you downloaded earlier.

Now inside the body tag we create a canvas and give it an id mycanvas and setting the width and height to 256.

&lg;canvas id="mycanvas" width="256" height=“256">

Next we will write the javascript code that will do the drawing for us using the Doughnut chart data we provide. Note! In this tutorial I have hard coded the values, but in real life scenario you may fetch the data from some other file or database and render the chart accordingly.

$(document).ready(function(){
//some code goes here...
});

The above code tells to run the javascript only after the page has loaded. Next, we get the canvas using the canvas id we assigned earlier. For this write the following code.

The above code tells us that we have three sectors having values 270, 50 and 40 respectively. We have set the color of the sectors to cornflowerblue, light green and orange. The highlight tells us that when the user will move the mouse over the sectors its will be highlighted and the assigned color will be used.

Now its time to draw the doughnut chart on the canvas. For this we will write the last piece of code.