This article will show you how to build a Pie Chart using the HTML5 canvas
Final Result
See the Pen Pie Chart Canvas HTML5 by Jonathan klughertz (@klugjo) on CodePen.
Project Description
This mini project / tutorial will give you an introduction on how to draw shapes in the canvas.
HTML
In our HTML file, we will simply insert a <canvas>
element and specify a width and height.
<canvas id="canvas" width="600" height="600"></canvas> |
Draw a pie slice
Let’s start by drawing a single Pie slice.
Canvas initialization
Let’s create a draw()
function that will be executed on a window.onload
. We can then retrieve our canvas by it’s id
and create our context. The context objet is what will be used to draw our lines.
function draw() { |
Draw a Pie Slice
To draw a Pie slice, we will:
- Move to the (200, 200) coordinates
- Start drawing an Arc with 120 radius and the center at (200, 200) and an angle of 0.3 PI
- Continue tracing a line all the way back to the center
Here is the code
function draw() { |
You might have realised that the initial line is drawn automatically: when we start drawing the arc, the path will automatically be linked from the initial position.
Here is what we have so far:
Draw the entire Pie
We will start with an array of angles which sum equals 2 PI and draw the all the slices.
We will also add a list of colours and for each slice, pick one and fill the slice with that color.
function draw() { |
And this is where we are at:
Separate the slices
The last step consists of creating space in between the pie slices.
For each slice, the center has to be offset by (cos(mediumAngle) * offset, sin(mediumAngle) * offset)
where:
mediumAngle
is the angle formed by the origin and the slice bisectoroffset
is the base offset
All that is left to do is to implement that change:
function draw() { |
And this is the final result:
See the Pen Pie Chart Canvas HTML5 by Jonathan klughertz (@klugjo) on CodePen.
Hope you have enjoyed this. Leave your questions in the comments below.