yoga1290

HTML5 Canvas Charts

Apr 15th, 2012
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 5 1.69 KB | None | 0 0
  1. //any better fix,email me [email protected]
  2. <html>
  3. <head>
  4. <title>Circluar Chart</title>
  5. </head>
  6. <body>
  7.  
  8.  
  9. <canvas id="canvas" width="400" height="400"></canvas>
  10. <canvas id="canvas2"    width="200" height="200"></canvas>
  11.  
  12. <script>
  13. function    drawChart(canvasID,array)
  14. {
  15.     var i,sum=0;
  16.     for(i=0;i<array.length;i++)
  17.         sum+=array[i];
  18.     var canvas = document.getElementById(canvasID);
  19.     var context = canvas.getContext("2d");
  20.     var centerX = canvas.width / 2;
  21.     var centerY = canvas.height / 2;
  22.     var radius = Math.min(centerX,centerY);
  23.     var startingAngle,endingAngle;
  24.     var lastAngle = 0;
  25.     var counterclockwise = false;
  26.     //anything better than black!
  27.     oldColor="#000000";
  28.     array.sort();
  29.     // Draw the 1s with bigger area first
  30.     for(i=array.length-1;i>=0;i--)
  31.     {
  32.         context.beginPath();
  33.         startingAngle=lastAngle;
  34.         endingAngle=startingAngle+Math.PI*2*array[i]/sum;
  35.         context.arc(centerX, centerY, radius, startingAngle, endingAngle, counterclockwise);
  36.         context.closePath();
  37.         //pick a different random color ,other than the last 1
  38.         while(context.fillStyle==oldColor)
  39.             context.fillStyle="#"+(Math.floor(Math.random()*parseInt("FFFFFF",16))).toString(16).toUpperCase();
  40.         oldColor=context.fillStyle;
  41.             context.fill();    
  42.         context.beginPath(); // begin custom shape
  43.         context.moveTo(centerX, centerY);
  44.         context.lineTo(centerX+Math.cos(startingAngle)*radius ,centerY+Math.sin(startingAngle)*radius);
  45.         context.lineTo(centerX+Math.cos(endingAngle)*radius ,centerY+Math.sin(endingAngle)*radius);
  46.         context.lineTo(centerX,centerY);
  47.         context.closePath();
  48.         context.fill();
  49.         lastAngle=endingAngle;
  50.     }
  51. }
  52.  
  53.  
  54. drawChart("canvas",[1,2,3]);
  55. drawChart("canvas2",[1,3,9]);
  56. </script>
  57. </body>
  58. </html>
Advertisement
Add Comment
Please, Sign In to add comment