Home » bar graph » Simple Pie Chart in Canvas

Simple Pie Chart in Canvas

To create Pie Chart in Canvas first draw canvas

<br />
&lt;canvas id=&quot;canvas&quot; width=&quot;400&quot; height=&quot;400&quot; style=&quot;border:1px solid #000000;&quot;&gt;<br />
&lt;/canvas&gt;<br />

then execute JavaScript code as below

var myColor = [&quot;#ECD078&quot;, &quot;#D95B43&quot;, &quot;#C02942&quot;, &quot;#542437&quot;, &quot;#53777A&quot;];<br />
var myData = [10, 30, 20, 60, 40];</p>
<p>function getTotal() {<br />
  var myTotal = 0;<br />
  for (var j = 0; j &lt; myData.length; j++) {<br />
    myTotal += (typeof myData[j] == 'number') ? myData[j] : 0;<br />
  }<br />
  return myTotal;<br />
}</p>
<p>function plotData() {<br />
  var canvas;<br />
  var ctx;<br />
  var lastend = 0;<br />
  var myTotal = getTotal();</p>
<p>  canvas = document.getElementById(&quot;canvas&quot;);<br />
  ctx = canvas.getContext(&quot;2d&quot;);<br />
  ctx.clearRect(0, 0, canvas.width, canvas.height);</p>
<p>  for (var i = 0; i &lt; myData.length; i++) {<br />
    ctx.fillStyle = myColor[i];<br />
    ctx.beginPath();<br />
    ctx.moveTo(200, 150);<br />
    ctx.arc(200, 150, 150, lastend, lastend +<br />
      (Math.PI * 2 * (myData[i] / myTotal)), false);<br />
    ctx.lineTo(200, 150);<br />
    ctx.fill();<br />
    lastend += Math.PI * 2 * (myData[i] / myTotal);<br />
  }<br />
}</p>
<p>plotData();<br />

jsFiddle link

Leave a Reply

Subscribe

Join 901 other subscribers