Advertisement
Guest User

zerzerz

a guest
Sep 30th, 2014
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.46 KB | None | 0 0
  1. //makeDoughnutChart draw a circle graph with values table.
  2. function makeDoughnutChart(cx, cy, radius, values) {
  3. context.save();
  4.  
  5. // Compute the sum of all values
  6. var sum=0;
  7. for(var n=0; n < values.length; n++) {
  8. sum += values[n];
  9. }
  10.  
  11. //Initialization of red green blue colors.
  12. var red = 0;
  13. var green = 0;
  14. var blue = 0;
  15.  
  16. //starting and ending angles of each pie section
  17. var startingAngle = 0;
  18. var endAngle = 0;
  19. //The percentage the current value represents, compare to the total,
  20. // we are in a closed circle, the sum is 100%
  21. var percentage;
  22.  
  23. //We draw in grey the outline of the section.
  24. context.strokeStyle = "grey";
  25.  
  26. // Draw the pie chart, clockwise, à la HTML5
  27. //for (var i=values.length-1; i> 0; i--) { // for ccw display
  28. for(var i = 0; i < values.length; i++) {
  29. context.beginPath(); //Begin a new path.
  30.  
  31. // We change the colors depending on the i-value. Just a trick based
  32. // on the modulo. Will produce different colors for the pie sections
  33. switch (i%3) {
  34. case 0: //If i modulo 3 equals 0:
  35. red += 80; //We add red.
  36. break;
  37. case 1: //If i modulo 3 equals 1:
  38. green += 80; //We add green.
  39. break;
  40. case 2: //If i modulo 3 equals 2:
  41. blue += 80; //We add blue.
  42. break;
  43. default: //If there is an error.
  44. alert("we have encountered an error");
  45. return ; //and we stop makePieChart.
  46. }
  47. context.fillStyle = "rgb(" + red + "," + green + "," + blue +")";
  48.  
  49. // percentage of the circle for current section, will give the angles
  50. percentage = values[i] / parseFloat(sum);
  51. endAngle = startingAngle + Math.PI*2*percentage;
  52.  
  53. // draw an arc between starting angle and end angle.
  54. context.arc(cx, cy, radius, startingAngle, endAngle);
  55. // draw a line between end angle and center of circle.
  56. context.lineTo(cx, cy);
  57.  
  58. //The next starting angle is the current end angle.
  59. startingAngle = endAngle;
  60.  
  61. context.fill(); // draw pie section
  62. context.stroke(); // draw the outline.
  63. context.closePath(); // Close the path.
  64.  
  65. context.restore();
  66. }
  67.  
  68. context.arc(300, 300, 50, 0, 2*Math.PI);
  69. context.fillStyle="white";
  70. context.fill();
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement