Anil Samal Anil Samal - 2 months ago 29
AngularJS Question

How to draw a multi level pie chart using html5 canvas?

I'm trying to make a

pie-chart
shape on a
canvas
element, however I can't find any function that does this by itself.

Is there an easy way to do a
pie chart like below image


This pie indicates the progress of each slice?

Answer

Here's a starting example for you that draws arcs using a recallable function:

Remember that the starting & ending arc angles are Radians. You can convert degrees to radians like this: radians = degrees * Math.PI/180

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
ctx.lineWidth = 2;
ctx.font = '14px verdana';

var PI2 = Math.PI * 2;
var myColor = ["Green", "Red", "Blue"];
var myData = [30, 15, 38, 22, 30, 20, 10];
var cx = 150;
var cy = 150;
var radius = 100;

ctx.globalAlpha=0.50;
pieChart(myData, myColor);
ctx.globalAlpha=1.00;

function pieChart(data, colors){
  // calc data total
  var total = 0;
  for (var i = 0; i < data.length; i++) {
    total += data[i];
  }
  // calc sweep angles for each piece of pie
  var sweeps = []
  for (var i = 0; i < data.length; i++) {
    sweeps.push(data[i] / total * PI2);
  }
  // draw outer pie
  var accumAngle = 0;
  for (var i = 0; i < sweeps.length; i++) {
    var f=randomColor();
    drawWedge(radius, accumAngle, accumAngle + sweeps[i], f, data[i]);
    accumAngle += sweeps[i];
  }
  // draw inner percent-complete wedges
  var accumAngle = 0;
  for (var i = 0; i < sweeps.length; i++) {
    var r=radius*(Math.random()*70+20)/100;
    var f=randomColor();
    drawWedge(r,accumAngle, accumAngle + sweeps[i], f, data[i]);
    accumAngle += sweeps[i];
  }  
}

function drawWedge(radius, startAngle, endAngle, fill, label) {
  // draw the wedge
  ctx.beginPath();
  ctx.moveTo(cx, cy);
  ctx.arc(cx, cy, radius, startAngle, endAngle, false);
  ctx.closePath();
  ctx.fillStyle = fill;
  ctx.strokeStyle = 'white';
  ctx.fill();
  ctx.stroke();
}

function randomColor(){ 
    return('#'+(Math.floor(Math.random() * 0x1000000) + 0x1000000).toString(16).substr(1));
}
body{ background-color: ivory; }
#canvas{border:1px solid red; }
<canvas id="canvas" width=512 height=512></canvas>

Comments