Developing a PieChart in HTML5 Using Canvas

Introduction

This article shows how to use the HTML5 canvas element to create a simple Pie Chart.

What is a Pie Chart?

A Pie Chart or a Circular Graph is used to represent data graphically. It gets its name by how it looks, just like a circular pie that has been divided into several slices. A Pie Chart is helpful when graphing qualitative data where the information describes a trait or attribute. But it does not describe a numerical information. Each attribute represents a different slice of the pie.

It is a circular chart that is divided into sectors.

Use of Pie Chart

Pie Charts are widely used in the business world and the mass media.

Disadvantage of Pie Charts

  • It cannot show more than a few values without separating the "slices" from the data they represent. When slices become too small, Pie Charts must rely on colors, textures or arrows so the reader can understand them. This makes them unsuitable for use with larger amounts of data.
  • Pie Charts also take up a larger amount of space on the page compared to bar charts, that do not need to have separate legends, and can also display other values such as averages or targets at the same time.

Step 1

We first define the element using the canvas tag. Note that the id, height, and width are a must.

<canvas id="myCanvas" width="600" height="300" style="border: 1px solid black;"></canvas>

 

Step 2

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

<script type="text/javascript">

    var canvas = document.getElementById('mycanvas');

    var ctx = canvas.getContext("2d");

</script>

Step 3

In the following we will create a "PieChart()" function in which we define the variables, methods, properties and constants.

function PieChart(canvasId, data) {

            // user defined properties

            this.canvas = document.getElementById(canvasId);

            this.data = data;

 

            // constants

            this.padding = 10;

            this.legendBorder = 2;

            this.pieBorder = 5;

            this.colorLabelSize = 20;

            this.borderColor = "#555";

            this.shadowColor = "#777";

            this.shadowBlur = 10;

            this.shadowX = 2;

            this.shadowY = 2;

            this.font = "16pt Calibri";

 

            // relationships

            this.context = this.canvas.getContext("2d");

            this.legendWidth = this.getLegendWidth();

            this.legendX = this.canvas.width - this.legendWidth;

            this.legendY = this.padding;

            this.pieAreaWidth = (this.canvas.width - this.legendWidth);

            this.pieAreaHeight = this.canvas.height;

            this.pieX = this.pieAreaWidth / 2;

            this.pieY = this.pieAreaHeight / 2;

            this.pieRadius = (Math.min(this.pieAreaWidth, this.pieAreaHeight) / 2) - (this.padding);

 

            // draw Pie Chart

            this.drawPieBorder();

            this.drawSlices();

            this.drawLegend();

        }

 

Step 4

In the following we get the legend width on the basis of the size of the label text. After getting the legend width we will apply the loop through all the labels and determine which label is longest. In this step we will determine the label width.

PieChart.prototype.getLegendWidth = function ()

{

   this.context.font = this.font;

   var labelWidth = 0;

 

   for (var n = 0; n < this.data.length; n++)

     {

       var label = this.data[n].label;

       labelWidth = Math.max(labelWidth, this.context.measureText(label).width);

     }

 

   return labelWidth + (this.padding * 2) + this.legendBorder + this.colorLabelSize;

};

Step 5

In the following we will draw the Pie Chart border and apply the properties (such as fillStyle):

PieChart.prototype.drawPieBorder = function ()

{

   var context = this.context;

   context.save();

   context.fillStyle = "white";

   context.shadowColor = this.shadowColor;

   context.shadowBlur = this.shadowBlur;

   context.shadowOffsetX = this.shadowX;

   context.shadowOffsetY = this.shadowY;

   context.beginPath();

   context.arc(this.pieX, this.pieY, this.pieRadius + this.pieBorder, 0, Math.PI * 2, false);

   context.fill();

   context.closePath();

   context.restore();

};

Step 6

In the following we will draw the slices of a Pie Chart.

PieChart.prototype.drawSlices = function ()

{

   var context = this.context;

   context.save();

   var total = this.getTotalValue();

   var startAngle = 0;

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

       var slice = this.data[n];

 

       // draw slice

       var sliceAngle = 2 * Math.PI * slice.value / total;

       var endAngle = startAngle + sliceAngle;

 

       context.beginPath();

       context.moveTo(this.pieX, this.pieY);

       context.arc(this.pieX, this.pieY, this.pieRadius, startAngle, endAngle, false);

       context.fillStyle = slice.color;

       context.fill();

       context.closePath();

       startAngle = endAngle;

   }

   context.restore();

};

Step 7

In the following we will get the total value of the Labels through the data by applying a loop and then adding up each value.

PieChart.prototype.getTotalValue = function ()

{

   var data = this.data;

   var total = 0;

 

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

     {

       total += data[n].value;

     }

 

   return total;

};

Step 8

In the following we will first draw the legend and after that draw the legend labels.

PieChart.prototype.drawLegend = function ()

{

   var context = this.context;

   context.save();

   var labelX = this.legendX;

   var labelY = this.legendY;

 

   context.strokeStyle = "black";

   context.lineWidth = this.legendBorder;

   context.font = this.font;

   context.textBaseline = "middle";

 

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

       var slice = this.data[n];

 

       // draw legend label

       context.beginPath();

       context.rect(labelX, labelY, this.colorLabelSize, this.colorLabelSize);

       context.closePath();

       context.fillStyle = slice.color;

       context.fill();

       context.stroke();

 

       context.fillStyle = "black";

       context.fillText(slice.label, labelX + this.colorLabelSize + this.padding, labelY + this.colorLabelSize / 2);

 

       labelY += this.colorLabelSize + this.padding;

   }

   context.restore();

};

Step 9

In the following, window onload we will call the PieChart() function that brings the slices together.

window.onload = function ()

{

   var data = [{

       label: "Eating",

       value: 4,

       color: "red"

   }, {

       label: "Working",

       value: 8,

       color: "blue"

   }, {

       label: "Sleeping",

       value: 8,

       color: "green"

   }, {

       label: "Playing]",

       value: 4,

       color: "yellow"

   }, {

       label: "Entertainment",

       value: 3,

       color: "violet"

   }];

 

   new PieChart("myCanvas", data);

};

 

Example

 

<!DOCTYPE html>

 

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">

<head>

    <meta charset="utf-8" />

    <title>Pie Chart in HTML5</title>

    <script>

 

        function PieChart(canvasId, data) {

            // user defined properties

            this.canvas = document.getElementById(canvasId);

            this.data = data;

 

            // constants

            this.padding = 10;

            this.legendBorder = 2;

            this.pieBorder = 5;

            this.colorLabelSize = 20;

            this.borderColor = "#555";

            this.shadowColor = "#777";

            this.shadowBlur = 10;

            this.shadowX = 2;

            this.shadowY = 2;

            this.font = "16pt Calibri";

 

            // relationships

            this.context = this.canvas.getContext("2d");

            this.legendWidth = this.getLegendWidth();

            this.legendX = this.canvas.width - this.legendWidth;

            this.legendY = this.padding;

            this.pieAreaWidth = (this.canvas.width - this.legendWidth);

            this.pieAreaHeight = this.canvas.height;

            this.pieX = this.pieAreaWidth / 2;

            this.pieY = this.pieAreaHeight / 2;

            this.pieRadius = (Math.min(this.pieAreaWidth, this.pieAreaHeight) / 2) - (this.padding);

 

            // draw Pie Chart

            this.drawPieBorder();

            this.drawSlices();

            this.drawLegend();

        }

 

        PieChart.prototype.getLegendWidth = function () {

 

            this.context.font = this.font;

            var labelWidth = 0;

 

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

                var label = this.data[n].label;

                labelWidth = Math.max(labelWidth, this.context.measureText(label).width);

            }

 

            return labelWidth + (this.padding * 2) + this.legendBorder + this.colorLabelSize;

        };

 

        PieChart.prototype.drawPieBorder = function () {

            var context = this.context;

            context.save();

            context.fillStyle = "white";

            context.shadowColor = this.shadowColor;

            context.shadowBlur = this.shadowBlur;

            context.shadowOffsetX = this.shadowX;

            context.shadowOffsetY = this.shadowY;

            context.beginPath();

            context.arc(this.pieX, this.pieY, this.pieRadius + this.pieBorder, 0, Math.PI * 2, false);

            context.fill();

            context.closePath();

            context.restore();

        };

 

        PieChart.prototype.drawSlices = function () {

            var context = this.context;

            context.save();

            var total = this.getTotalValue();

            var startAngle = 0;

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

                var slice = this.data[n];

 

                // draw slice

                var sliceAngle = 2 * Math.PI * slice.value / total;

                var endAngle = startAngle + sliceAngle;

 

                context.beginPath();

                context.moveTo(this.pieX, this.pieY);

                context.arc(this.pieX, this.pieY, this.pieRadius, startAngle, endAngle, false);

                context.fillStyle = slice.color;

                context.fill();

                context.closePath();

                startAngle = endAngle;

            }

            context.restore();

        };

 

        PieChart.prototype.getTotalValue = function () {

            var data = this.data;

            var total = 0;

 

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

                total += data[n].value;

            }

 

            return total;

        };

 

        PieChart.prototype.drawLegend = function () {

            var context = this.context;

            context.save();

            var labelX = this.legendX;

            var labelY = this.legendY;

 

            context.strokeStyle = "black";

            context.lineWidth = this.legendBorder;

            context.font = this.font;

            context.textBaseline = "middle";

 

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

                var slice = this.data[n];

 

                // draw legend label

                context.beginPath();

                context.rect(labelX, labelY, this.colorLabelSize, this.colorLabelSize);

                context.closePath();

                context.fillStyle = slice.color;

                context.fill();

                context.stroke();

 

                context.fillStyle = "black";

                context.fillText(slice.label, labelX + this.colorLabelSize + this.padding, labelY + this.colorLabelSize / 2);

 

                labelY += this.colorLabelSize + this.padding;

            }

            context.restore();

        };

 

        window.onload = function () {

            var data = [{

                label: "Eating",

                value: 4,

                color: "red"

            }, {

                label: "Working",

                value: 8,

                color: "blue"

            }, {

                label: "Sleeping",

                value: 8,

                color: "green"

            }, {

                label: "Playing",

                value: 4,

                color: "yellow"

            }, {

                label: "Entertainment",

                value: 3,

                color: "violet"

            }];

 

            new PieChart("myCanvas", data);

        };

    </script>

</head>

<body>

    <canvas id="myCanvas" width="600" height="300" style="border: 1px solid black;"></canvas>

</body>

</html>


Output

pie.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all