How To Create Pie Chart In Html5
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.
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.
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
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.
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 bisector -
offset
is the base offset
All that is left to do is to implement that change:
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.
How To Create Pie Chart In Html5
Source: https://www.codeblocq.com/2016/04/Create-a-Pie-Chart-with-HTML5-canvas/
Posted by: cliftonhowles1979.blogspot.com
0 Response to "How To Create Pie Chart In Html5"
Post a Comment