-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path17.2. The pie chart.html
54 lines (47 loc) · 1.46 KB
/
17.2. 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
48
49
50
51
52
53
54
<canvas width="600" height="300"></canvas>
<script>
const results = [
{name: "Satisfied", count: 1043, color: "lightblue"},
{name: "Neutral", count: 563, color: "lightgreen"},
{name: "Unsatisfied", count: 510, color: "pink"},
{name: "No comment", count: 175, color: "silver"}
];
let cx = document.querySelector("canvas").getContext("2d");
let total = results.reduce((sum, {count}) => sum + count, 0);
let currentAngle = -0.5 * Math.PI;
let centerX = 300, centerY = 150;
// Add code to draw the slice labels in this loop.
for (let result of results) {
let sliceAngle = (result.count / total) * 2 * Math.PI;
// Draw chart
cx.beginPath();
cx.arc(centerX, centerY, 100, currentAngle, currentAngle + sliceAngle);
cx.lineTo(centerX, centerY);
cx.fillStyle = result.color;
cx.fill();
// Draw label
let avgAngle = currentAngle + sliceAngle / 2;
let offset = 10;
let textX = Math.cos(-avgAngle) * 100 + 300;
let textY = 150 - Math.sin(-avgAngle) * 100;
if (textX > 300) {
textX += offset;
cx.textAlign = "left";
} else {
textX -= offset;
cx.textAlign = "right";
}
if (textY > 150) {
textY += offset;
cx.textBaseline = "top";
} else {
textY -= offset;
cx.textBaseline = "bottom";
}
cx.font = "18px Garamond";
cx.fillStyle = "black";
cx.fillText(result.name, textX, textY);
// Update angle
currentAngle += sliceAngle;
}
</script>