yoga1290

HTML5 Canvas Charts

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