Skip to content

Simple Pie Chart in Canvas

To create Pie Chart in Canvas first draw canvas

<canvas id="canvas" width="400" height="400" style="border:1px solid #000000;">
</canvas>

then execute JavaScript code as below

var myColor = ["#ECD078", "#D95B43", "#C02942", "#542437", "#53777A"];
var myData = [10, 30, 20, 60, 40];

function getTotal() {
  var myTotal = 0;
  for (var j = 0; j < myData.length; j++) {
    myTotal += (typeof myData[j] == 'number') ? myData[j] : 0;
  }
  return myTotal;
}

function plotData() {
  var canvas;
  var ctx;
  var lastend = 0;
  var myTotal = getTotal();

  canvas = document.getElementById("canvas");
  ctx = canvas.getContext("2d");
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  for (var i = 0; i < myData.length; i++) {
    ctx.fillStyle = myColor[i];
    ctx.beginPath();
    ctx.moveTo(200, 150);
    ctx.arc(200, 150, 150, lastend, lastend +
      (Math.PI * 2 * (myData[i] / myTotal)), false);
    ctx.lineTo(200, 150);
    ctx.fill();
    lastend += Math.PI * 2 * (myData[i] / myTotal);
  }
}

plotData();

jsFiddle link

Leave a Reply

%d bloggers like this: