banner



How To Create Pie Chart In Html5

  • Updated date Dec 09, 2019
  • 22.6k
  • 2

This article shows how to use the HTML5 canvas element to create a simple pie chart.

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 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.

The 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.

  1. < script type = "text/javascript" >
  2.     varcanvas  = document .getElementById('mycanvas');
  3.     varctx  = canvas .getContext("2d");
  4. </ script >

Step 3

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

  1. function PieChart(canvasId, data) {
  2.             // user defined properties
  3. this.canvas  = document .getElementById(canvasId);
  4. this.data  = data;
  5.             // constants
  6. this.padding  = 10 ;
  7. this.legendBorder  = 2 ;
  8. this.pieBorder  = 5 ;
  9. this.colorLabelSize  = 20 ;
  10. this.borderColor  = "#555" ;
  11. this.shadowColor  = "#777" ;
  12. this.shadowBlur  = 10 ;
  13. this.shadowX  = 2 ;
  14. this.shadowY  = 2 ;
  15. this.font  = "16pt Calibri" ;
  16.             // relationships
  17. this this.context  = this.canvas.getContext("2d");
  18. this this.legendWidth  = this.getLegendWidth();
  19. this this.legendX  = this.canvas.width - this.legendWidth;
  20. this this.legendY  = this.padding;
  21. this.pieAreaWidth  = (this.canvas.width - this.legendWidth);
  22. this this.pieAreaHeight  = this.canvas.height;
  23. this this.pieX  = this.pieAreaWidth / 2;
  24. this this.pieY  = this.pieAreaHeight / 2;
  25. this.pieRadius  = (Math.min(this.pieAreaWidth, this.pieAreaHeight) / 2) - (this.padding);
  26.             // draw Pie Chart
  27.             this.drawPieBorder();
  28.             this.drawSlices();
  29.             this.drawLegend();
  30.         }

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.

  1. PieChart.prototype.getLegendWidth  = function  ()
  2. {
  3. this this.context.font  = this.font;
  4.    varlabelWidth  = 0 ;
  5.    for (varn  = 0 ; n < this.data.length ; n++)
  6.      {
  7.        varlabel  = this .data[n].label;
  8. labelWidth  = Math .max(labelWidth, this.context.measureText(label).width);
  9.      }
  10.    return labelWidth + (this.padding * 2) + this.legendBorder + this.colorLabelSize;
  11. };

Step 5

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

  1. PieChart.prototype.drawPieBorder  = function  ()
  2. {
  3.    varcontext  = this .context;
  4.    context.save();
  5. context.fillStyle  = "white" ;
  6. context.shadowColor  = this .shadowColor;
  7. context.shadowBlur  = this .shadowBlur;
  8. context.shadowOffsetX  = this .shadowX;
  9. context.shadowOffsetY  = this .shadowY;
  10.    context.beginPath();
  11.    context.arc(this.pieX, this.pieY, this.pieRadius + this.pieBorder, 0, Math.PI * 2, false);
  12.    context.fill();
  13.    context.closePath();
  14.    context.restore();
  15. };

Step 6

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

  1. PieChart.prototype.drawSlices  = function  ()
  2. {
  3.    varcontext  = this .context;
  4.    context.save();
  5.    vartotal  = this .getTotalValue();
  6.    varstartAngle  = 0 ;
  7.    for (varn  = 0 ; n < this.data.length ; n++) {
  8.        varslice  = this .data[n];
  9.        // draw slice
  10.        varsliceAngle  = 2  * Math.PI * slice.value / total;
  11.        varendAngle  = startAngle  + sliceAngle;
  12.        context.beginPath();
  13.        context.moveTo(this.pieX, this.pieY);
  14.        context.arc(this.pieX, this.pieY, this.pieRadius, startAngle, endAngle, false);
  15. context.fillStyle  = slice .color;
  16.        context.fill();
  17.        context.closePath();
  18. startAngle  = endAngle ;
  19.    }
  20.    context.restore();
  21. };

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.

  1. PieChart.prototype.getTotalValue  = function  ()
  2. {
  3.    vardata  = this .data;
  4.    vartotal  = 0 ;
  5.    for (varn  = 0 ; n < data.length ; n++)
  6.      {
  7.        total += data[n].value;
  8.      }
  9.    return total;
  10. };

Step 8

In the following, we willfirst draw the legend and after that draw the legend labels.

  1. PieChart.prototype.drawLegend  = function  ()
  2. {
  3.    varcontext  = this .context;
  4.    context.save();
  5.    varlabelX  = this .legendX;
  6.    varlabelY  = this .legendY;
  7. context.strokeStyle  = "black" ;
  8. context.lineWidth  = this .legendBorder;
  9. context.font  = this .font;
  10. context.textBaseline  = "middle" ;
  11.    for (varn  = 0 ; n < this.data.length ; n++) {
  12.        varslice  = this .data[n];
  13.        // draw legend label
  14.        context.beginPath();
  15.        context.rect(labelX, labelY, this.colorLabelSize, this.colorLabelSize);
  16.        context.closePath();
  17. context.fillStyle  = slice .color;
  18.        context.fill();
  19.        context.stroke();
  20. context.fillStyle  = "black" ;
  21.        context.fillText(slice.label, labelX + this.colorLabelSize + this.padding, labelY + this.colorLabelSize / 2);
  22.        labelY += this.colorLabelSize + this.padding;
  23.    }
  24.    context.restore();
  25. };

Step 9

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

  1. window.onload  = function  ()
  2. {
  3.    vardata  = [{
  4.        label: "Eating",
  5.        value: 4,
  6.        color: "red"
  7.    }, {
  8.        label: "Working",
  9.        value: 8,
  10.        color: "blue"
  11.    }, {
  12.        label: "Sleeping",
  13.        value: 8,
  14.        color: "green"
  15.    }, {
  16.        label: "Playing]",
  17.        value: 4,
  18.        color: "yellow"
  19.    }, {
  20.        label: "Entertainment",
  21.        value: 3,
  22.        color: "violet"
  23.    }];
  24.    new PieChart("myCanvas", data);
  25. };

Example

  1. <!DOCTYPE html >
  2. < html lang = "en" xmlns = "http://www.w3.org/1999/xhtml" >
  3. < head >
  4. < meta charset = "utf-8" />
  5. < title > Pie Chart in HTML5 </ title >
  6. < script >
  7.         function PieChart(canvasId, data) {
  8.             // user defined properties
  9. this.canvas  = document .getElementById(canvasId);
  10. this.data  = data;
  11.             // constants
  12. this.padding  = 10 ;
  13. this.legendBorder  = 2 ;
  14. this.pieBorder  = 5 ;
  15. this.colorLabelSize  = 20 ;
  16. this.borderColor  = "#555" ;
  17. this.shadowColor  = "#777" ;
  18. this.shadowBlur  = 10 ;
  19. this.shadowX  = 2 ;
  20. this.shadowY  = 2 ;
  21. this.font  = "16pt Calibri" ;
  22.             // relationships
  23. this this.context  = this.canvas.getContext("2d");
  24. this this.legendWidth  = this.getLegendWidth();
  25. this this.legendX  = this.canvas.width - this.legendWidth;
  26. this this.legendY  = this.padding;
  27. this.pieAreaWidth  = (this.canvas.width - this.legendWidth);
  28. this this.pieAreaHeight  = this.canvas.height;
  29. this this.pieX  = this.pieAreaWidth / 2;
  30. this this.pieY  = this.pieAreaHeight / 2;
  31. this.pieRadius  = (Math.min(this.pieAreaWidth, this.pieAreaHeight) / 2) - (this.padding);
  32.             // draw Pie Chart
  33.             this.drawPieBorder();
  34.             this.drawSlices();
  35.             this.drawLegend();
  36.         }
  37. PieChart.prototype.getLegendWidth  = function  () {
  38. this this.context.font  = this.font;
  39.             varlabelWidth  = 0 ;
  40.             for (varn  = 0 ; n < this.data.length ; n++) {
  41.                 varlabel  = this .data[n].label;
  42. labelWidth  = Math .max(labelWidth, this.context.measureText(label).width);
  43.             }
  44.             return labelWidth + (this.padding * 2) + this.legendBorder + this.colorLabelSize;
  45.         };
  46. PieChart.prototype.drawPieBorder  = function  () {
  47.             varcontext  = this .context;
  48.             context.save();
  49. context.fillStyle  = "white" ;
  50. context.shadowColor  = this .shadowColor;
  51. context.shadowBlur  = this .shadowBlur;
  52. context.shadowOffsetX  = this .shadowX;
  53. context.shadowOffsetY  = this .shadowY;
  54.             context.beginPath();
  55.             context.arc(this.pieX, this.pieY, this.pieRadius + this.pieBorder, 0, Math.PI * 2, false);
  56.             context.fill();
  57.             context.closePath();
  58.             context.restore();
  59.         };
  60. PieChart.prototype.drawSlices  = function  () {
  61.             varcontext  = this .context;
  62.             context.save();
  63.             vartotal  = this .getTotalValue();
  64.             varstartAngle  = 0 ;
  65.             for (varn  = 0 ; n < this.data.length ; n++) {
  66.                 varslice  = this .data[n];
  67.                 // draw slice
  68.                 varsliceAngle  = 2  * Math.PI * slice.value / total;
  69.                 varendAngle  = startAngle  + sliceAngle;
  70.                 context.beginPath();
  71.                 context.moveTo(this.pieX, this.pieY);
  72.                 context.arc(this.pieX, this.pieY, this.pieRadius, startAngle, endAngle, false);
  73. context.fillStyle  = slice .color;
  74.                 context.fill();
  75.                 context.closePath();
  76. startAngle  = endAngle ;
  77.             }
  78.             context.restore();
  79.         };
  80. PieChart.prototype.getTotalValue  = function  () {
  81.             vardata  = this .data;
  82.             vartotal  = 0 ;
  83.             for (varn  = 0 ; n < data.length ; n++) {
  84.                 total += data[n].value;
  85.             }
  86.             return total;
  87.         };
  88. PieChart.prototype.drawLegend  = function  () {
  89.             varcontext  = this .context;
  90.             context.save();
  91.             varlabelX  = this .legendX;
  92.             varlabelY  = this .legendY;
  93. context.strokeStyle  = "black" ;
  94. context.lineWidth  = this .legendBorder;
  95. context.font  = this .font;
  96. context.textBaseline  = "middle" ;
  97.             for (varn  = 0 ; n < this.data.length ; n++) {
  98.                 varslice  = this .data[n];
  99.                 // draw legend label
  100.                 context.beginPath();
  101.                 context.rect(labelX, labelY, this.colorLabelSize, this.colorLabelSize);
  102.                 context.closePath();
  103. context.fillStyle  = slice .color;
  104.                 context.fill();
  105.                 context.stroke();
  106. context.fillStyle  = "black" ;
  107.                 context.fillText(slice.label, labelX + this.colorLabelSize + this.padding, labelY + this.colorLabelSize / 2);
  108.                 labelY += this.colorLabelSize + this.padding;
  109.             }
  110.             context.restore();
  111.         };
  112. window.onload  = function  () {
  113.             vardata  = [{
  114.                 label: "Eating",
  115.                 value: 4,
  116.                 color: "red"
  117.             }, {
  118.                 label: "Working",
  119.                 value: 8,
  120.                 color: "blue"
  121.             }, {
  122.                 label: "Sleeping",
  123.                 value: 8,
  124.                 color: "green"
  125.             }, {
  126.                 label: "Playing",
  127.                 value: 4,
  128.                 color: "yellow"
  129.             }, {
  130.                 label: "Entertainment",
  131.                 value: 3,
  132.                 color: "violet"
  133.             }];
  134.             new PieChart("myCanvas", data);
  135.         };
  136. </ script >
  137. </ head >
  138. < body >
  139. < canvas id = "myCanvas" width = "600" height = "300" style = "border: 1px solid black;" > </ canvas >
  140. </ body >
  141. </ html >

Output

pie.jpg

How To Create Pie Chart In Html5

Source: https://www.c-sharpcorner.com/UploadFile/18ddf7/developing-a-piechart-in-html5-using-canvas/

Posted by: osbywaye1974.blogspot.com

0 Response to "How To Create Pie Chart In Html5"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel