11 May 2012

Simple Javascript Pie Chart using HTML5 Canvas tag


I had a look around today for a handy pie chart that I could quickly drop into a new web app I'm working on and it seems there's a lot of bloated solutions out there. I like to keep things short and sweet so I found this one online and edited it to make it a bit more user friendly. Enjoy!

Please see right hand pane before copying my code >>


//ADD THIS BETWEEN YOUR HEAD TAGS OR TO AN EXTERNAL JS FILE:
var pieProps = new Object()

function pieChart(canvas, radius, percentages, n, colors) {
 var canvas = document.getElementById(canvas)
 var a = pieProps.a = canvas.getContext("2d");
 pieProps.colors = colors
 pieProps.i = 0
 canvas.width = 3.5*radius;
 canvas.height = 2.5*radius;
 x = y = canvas.height/2;
 a.font = "bold 12px Arial";
 var u = 0;
 var v = 0;
 for (i=0;i < percentages.length;i++) {
  v += percentages[i];
  W(i)(x,y,radius,u,v);
  u = v;
  a.fillText(n[i], x+radius+10, y-radius/2+i*18);
 }
}

function W(x,y,r,u,v) {
 var a = pieProps.a
 if(r) {
  a.beginPath();
  a.moveTo(x,y);
  a.arc(x, y , r, (u||0)/50*Math.PI, (v||7)/50*Math.PI, 0);
  a.lineTo(x,y);
  a.fill();
 } else {
  a.fillStyle = '#'+pieProps.colors[pieProps.i++];
 }
 return W;
}

//ADD THIS TO YOUR PAGE SOMEWHERE:
<canvas id="c"> Your browser does not support the canvas element. </canvas>

//EXAMPLE USAGE:
<body onload="pieChart('c', 100, [70,25,15], ['Carbs','Protein','Fat'], ['CCCCCC','FFBF43','FF850D'])">

This code is adapted from http://reubencrane.com/canvas_pie.html

12 comments:

  1. Nice adaptation, glad I could help!

    ReplyDelete
  2. Great example. useful information. I am learn for Jquery script on

    ReplyDelete
  3. Nice coding. http://www.dreamdestinations.in/

    ReplyDelete
  4. nice things ..a great example
    If anyone want learn more about Cakephp image behavior...This is the nice blog to read...

    cakephplogics.blogspot.com

    ReplyDelete
  5. nice things ..a great example
    If anyone want learn more about Cakephp image behavior...This is the nice blog to read...

    http://cakephplogics.blogspot.com

    ReplyDelete
  6. Thank you for sharing. Good code. I have found an interesting chart http://www.pptstar.com/diagrams/pie-charts/, but do not know how I can use them. I want to try to make such chart on your example.

    ReplyDelete
  7. Excellent and very cool idea and the subject at the top of magnificence and I am happy to this post..Interesting post! Thanks for writing it. What's wrong with this kind of post exactly? It follows your previous guideline for post length as well as clarity..Website for school uk

    ReplyDelete
  8. Buy Mattress naz online on Treasurebox store items which you will be provide easily on a single click.

    ReplyDelete
  9. The explanation was excellent. I learned a lot! Thanks for sharing this resource.
    bitcoin books for children

    ReplyDelete