forked from marijnh/Eloquent-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path17_2_the_pie_chart.html
More file actions
40 lines (34 loc) · 1.12 KB
/
17_2_the_pie_chart.html
File metadata and controls
40 lines (34 loc) · 1.12 KB
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
<!doctype html>
<base href="https://eloquentjavascript.net/">
<script src="code/chapter/16_canvas.js"></script>
<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, 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>