1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8" />
5 <title>18-Canvas绘制饼状图</title>
6 <style>
7 * {
8 margin: 0;
9 padding: 0;
10 }
11 canvas {
12 display: block;
13 margin: 0 auto;
14 background: red;
15 }
16 </style>
17 </head>
18 <body>
19 <canvas width="500" height="400"></canvas>
20 <script>
21 // 1.拿到canvas
22 let oCanvas = document.querySelector("canvas");
23 // 2.从canvas中拿到绘图工具
24 let oCtx = oCanvas.getContext("2d");
25
26 // 1.计算圆心的位置
27 let rx = oCtx.canvas.width / 2;
28 let ry = oCtx.canvas.height / 2;
29
30 // 2.绘制第一个扇形
31 // oCtx.moveTo(rx, ry);
32 // oCtx.arc(rx, ry, 100, 0, Math.PI/2);
33 // oCtx.fillStyle = randomColor();
34 // oCtx.fill();
35
36 // 3.绘制第二个扇形
37 // oCtx.beginPath();
38 // oCtx.moveTo(rx, ry);
39 // oCtx.arc(rx, ry, 100, Math.PI/2, Math.PI);
40 // oCtx.fillStyle = randomColor();
41 // oCtx.fill();
42
43 // 4.绘制第三个扇形
44 // oCtx.beginPath();
45 // oCtx.moveTo(rx, ry);
46 // oCtx.arc(rx, ry, 100, Math.PI, Math.PI + Math.PI/2);
47 // oCtx.fillStyle = randomColor();
48 // oCtx.fill();
49
50 // 5.绘制第四个扇形
51 // oCtx.beginPath();
52 // oCtx.moveTo(rx, ry);
53 // oCtx.arc(rx, ry, 100, Math.PI + Math.PI/2, Math.PI * 2);
54 // oCtx.fillStyle = randomColor();
55 // oCtx.fill();
56
57 let startAngle = 0;
58 for (let i = 1; i <= 4; i++) {
59 let endAngle = (i * Math.PI) / 2;
60 oCtx.beginPath();
61 oCtx.moveTo(rx, ry);
62 oCtx.arc(rx, ry, 100, startAngle, endAngle);
63 oCtx.fillStyle = randomColor();
64 oCtx.fill();
65 startAngle = endAngle;
66 }
67
68 function randomColor() {
69 let r = Math.floor(Math.random() * 256);
70 let g = Math.floor(Math.random() * 256);
71 let b = Math.floor(Math.random() * 256);
72 return `rgb(${r},${g},${b})`;
73 };
74
75
76
77 // 定时器返回数据
78 // function qwe(a) {
79 // console.log(a);
80 // }
81
82 // function dsd() {
83 // setInterval(() => {
84 // let qwer = 1;
85 // qwe(qwer);
86 // }, 1000);
87 // }
88 // dsd();
89 </script>
90 </body>
91 </html>