Creating Pie Chart Using Canvas

Deepak Rai
1 min readOct 2, 2021

This article will help you to create pie chart using canvas.We need first one canvas element.

<canvas width=”800" height=”550" id=”canvasDeep” >

We will capture canvas element and get the context using javascript

var can = document.getElementById(‘canvasDeep’);
var ctx = can.getContext(‘2d’);

Next we need data to create our pie chart.

var colors = [“maroon”, “blue”, “yellow”, “navy”, “aqua”, “purple”,”red”,”maroon”, “blue”, “yellow”, “navy”, “aqua”];
var names=[“JAN”,”FEB”,”MAR”,”APR”,”MAY”,”JUNE”,”JULY”,”AUG”,”SEPT”,”OCT”,”NOV”,”DEC”];

Next we will need radius that can be calculated by using below code

var centerX=can.width/2;
var centerY=can.height/2 + 25;
var radius = (Math.min(can.width,can.height) / 2)-70;

and final loop which will draw arc

for (var i = 0; i<data.length; i++){
ctx.fillStyle = colors[i];
ctx.beginPath();
ctx.moveTo(centerX,centerY);
ctx.arc(centerX,centerY,radius,startAngle,startAngle+(Math.PI*2*(data[i]/total)),false);
ctx.lineTo(centerX,centerY);
ctx.rect(centerX+incrFactor,20,20,10);
ctx.fill();
ctx.fillStyle=”black”;
ctx.font=”bold 10pt Arial”;
ctx.fillText(names[i],centerX+incrFactor,15);
ctx.save();
ctx.translate(centerX,centerY);
ctx.rotate(startAngle);
var dx=Math.floor(can.width*0.5)-100;
var dy=Math.floor(can.height*0.20);
ctx.fillText(names[i],dx-100,dy-50);
ctx.restore();
startAngle += Math.PI*2*(data[i]/total);
incrFactor+=50;
}

You can get the full source code from below location

https://github.com/deepuRai/pie-chart-canvas

--

--