This repository has been archived by the owner on Mar 29, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 19
/
the_pie_chart.html
47 lines (39 loc) · 1.63 KB
/
the_pie_chart.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<!--
2 - The Pie Chart (19/3/2020)
Earlier in the chapter, we saw an example program that drew a pie chart. Modify this program so that the name of each category is shown next to the slice that represents it. Try to find a pleasing-looking way to automatically position this text that would work for other data sets as well. You may assume that categories are big enough to leave ample room for their labels.
You might need Math.sin and Math.cos again, which are described in Chapter 14.
-->
<!DOCTYPE html>
<canvas width="600" height="300"></canvas>
<script>
let cx = document.querySelector("canvas").getContext("2d");
let total = results.reduce(function(sum, choice) {
return sum + choice.count;
}, 0);
let currentAngle = -0.5 * Math.PI;
let centerX = 300;
let centerY = 150;
results.forEach(function(result) {
let sliceAngle = (result.count / total) * 2 * Math.PI;
cx.beginPath();
cx.arc(centerX, centerY, 100,
currentAngle, currentAngle + sliceAngle);
let middleAngle = currentAngle + 0.5 * sliceAngle;
let textX = Math.cos(middleAngle) * 120 + centerX;
let textY = Math.sin(middleAngle) * 120 + centerY;
cx.textBaseLine = "middle";
if (Math.cos(middleAngle) > 0) {
cx.textAlign = "left";
}
else {
cx.textAlign = "right";
}
cx.font = "15px sans-serif";
cx.fillStyle = "black";
cx.fillText(result.name, textX, textY);
currentAngle += sliceAngle;
cx.lineTo(centerX, centerY);
cx.fillStyle = result.color;
cx.fill();
});
</script>