Posted on

Pie charts in canvas

This post will be about making pie charts and doughnut chart with html5 canvas and plain javascript/coffeescript. As there are lot of other possible solutions for making really nice plots and charts, this tutorial is not intended to provide a complex and exhaustive solution.

Data and Colors

Before we want to make a chart we need data. For example this:


Segments variable is an array with 5 numbers, a partial values of our future chart.

As a next step we should steal a colorscheme from colorbrewer. This one:


Basic canvas setting

Now i will paste here a simple code for setting a canvas and creating some variables like central position and size of our chart



Drawing pie segments

Finally, lets draw our pie segments from data array to canvas.  Cumulative variable is here a temporal value of summed values of drawn segments. In each iteration over data array we precalculate startSegment and EndSegment variable. These are arcs in radians that are relevant for particular segment. Now with the combination of moveTo -> act -> lineTo it is possible to draw that segment. In the second part of iteration the label will be written.




Labeling segments

Firstly we need a diffArc variable that holds the size of that segment. LabelX ane labelY are then calculated from that size and with the help of goniometry – for X position Math.sin is used, for Y position Math.cos. Here you should use a halo/glow effects (html5rocks webpage should  should be a good inspiration) or the second choice is to draw a legend. This is a full example code for drawing a single label and should be put inside our iteration


Working example

See the Pen canvas coffeescript pie chart by Eidam (@eidam61) on CodePen.

Leave a Reply