Creating a simple pie chart with HTML5 Canvas

This week we take a look at how to use the HTML5 canvas element to create a simple pie chart. To begin, we need to define the element using the canvas tag. Please note the id, height, and width are required.

<canvas id=”canvas” width=”400″ height=”300″></canvas>

In order to interact with this canvas through Java script, we will need to first get the element by Id and then create a context.


<script type="text/javascript">

var canvas = document.getElementById(‘canvas’);

var ctx = canvas.getContext(“2d”);

</script>

These two steps are essentially all that is required to start drawing to the canvas. For this example, we will be drawing a simple pie chart, so let’s add some data. We’ll use some hard coded values for data in the interest of simplicity.

 

var data = [75,68,32,95,20,51];

var colors = [“#7E3817”, “#C35817”, “#EE9A4D”, “#A0C544”, “#348017”, “#307D7E”];

var center = [canvas.width / 2, canvas.height / 2];

var radius = Math.min(canvas.width, canvas.height) / 2;

var lastPosition = 0, total = 0;

 

Next we will need to get the total value of all the data being represented in the pie chart. This is required in order to scale the size of each slice correctly. To do this, we simply need to loop through the data array and add each value into the ‘total’ variable defined above.

 

for(var i in data) { total += data[i]; }

 

And finally, we are ready start using canvas to draw each slice of the pie. To do this, we will loop through the data array again and call the canvas methods to create and fill the shapes.

 

for (var i = 0; i < data.length; i++) {

ctx.fillStyle = colors[i];

ctx.beginPath();

ctx.moveTo(center[0],center[1]);

ctx.arc(center[0],center[1],radius,lastPosition,lastPosition+(Math.PI*2*(data[i]/total)),false);

ctx.lineTo(center[0],center[1]);

ctx.fill();

lastPosition += Math.PI*2*(data[i]/total);

}

 

Loading the page in an HTML5 enabled browser should result in our chart being rendered as follows.

 

pie_chart

 

Next week we will take a look at adding labels to the chart as well as adding some user interaction with animation.

Advertisements

2 Trackbacks to “Creating a simple pie chart with HTML5 Canvas”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: