Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //makeDoughnutChart draw a circle graph with values table.
- function makeDoughnutChart(cx, cy, radius, values) {
- context.save();
- // Compute the sum of all values
- var sum=0;
- for(var n=0; n < values.length; n++) {
- sum += values[n];
- }
- //Initialization of red green blue colors.
- var red = 0;
- var green = 0;
- var blue = 0;
- //starting and ending angles of each pie section
- var startingAngle = 0;
- var endAngle = 0;
- //The percentage the current value represents, compare to the total,
- // we are in a closed circle, the sum is 100%
- var percentage;
- //We draw in grey the outline of the section.
- context.strokeStyle = "grey";
- // Draw the pie chart, clockwise, à la HTML5
- //for (var i=values.length-1; i> 0; i--) { // for ccw display
- for(var i = 0; i < values.length; i++) {
- context.beginPath(); //Begin a new path.
- // We change the colors depending on the i-value. Just a trick based
- // on the modulo. Will produce different colors for the pie sections
- switch (i%3) {
- case 0: //If i modulo 3 equals 0:
- red += 80; //We add red.
- break;
- case 1: //If i modulo 3 equals 1:
- green += 80; //We add green.
- break;
- case 2: //If i modulo 3 equals 2:
- blue += 80; //We add blue.
- break;
- default: //If there is an error.
- alert("we have encountered an error");
- return ; //and we stop makePieChart.
- }
- context.fillStyle = "rgb(" + red + "," + green + "," + blue +")";
- // percentage of the circle for current section, will give the angles
- percentage = values[i] / parseFloat(sum);
- endAngle = startingAngle + Math.PI*2*percentage;
- // draw an arc between starting angle and end angle.
- context.arc(cx, cy, radius, startingAngle, endAngle);
- // draw a line between end angle and center of circle.
- context.lineTo(cx, cy);
- //The next starting angle is the current end angle.
- startingAngle = endAngle;
- context.fill(); // draw pie section
- context.stroke(); // draw the outline.
- context.closePath(); // Close the path.
- context.restore();
- }
- context.arc(300, 300, 50, 0, 2*Math.PI);
- context.fillStyle="white";
- context.fill();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement