1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>14-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 // 3.定义变量保存小方格的尺寸
26 let gridSize = 50;
27 // 4.拿到canvas的宽高
28 let canvasWidth = oCtx.canvas.width;
29 let canvasHeight = oCtx.canvas.height;
30 // 5.计算在垂直方向和水平方向可以绘制多少条横线
31 let row = Math.floor(canvasHeight / gridSize);
32 let col = Math.floor(canvasWidth / gridSize);
33 // 6.绘制垂直方向的横线
34 for(let i = 0; i < row; i++){
35 oCtx.beginPath();
36 oCtx.moveTo(0, i * gridSize - 0.5);
37 oCtx.lineTo(canvasWidth, i * gridSize - 0.5);
38 oCtx.strokeStyle = "#ccc";
39 oCtx.stroke();
40 }
41 // 7.绘制水平方向的横线
42 for(let i = 0; i < col; i++){
43 oCtx.beginPath();
44 oCtx.moveTo(i * gridSize - 0.5, 0);
45 oCtx.lineTo(i * gridSize - 0.5, canvasHeight);
46 oCtx.strokeStyle = "#ccc";
47 oCtx.stroke();
48 }
49
50 // 1.计算坐标系原点的位置
51 let originX = gridSize;
52 let originY = canvasHeight - gridSize;
53 // 2.计算X轴终点的位置
54 let endX = canvasWidth - gridSize;
55 // 3.绘制X轴
56 oCtx.beginPath();
57 oCtx.moveTo(originX, originY);
58 oCtx.lineTo(endX, originY);
59 oCtx.strokeStyle = "#000";
60 oCtx.stroke();
61 // 4.绘制X轴的箭头
62 oCtx.lineTo(endX - 10, originY + 5);
63 oCtx.lineTo(endX - 10, originY - 5);
64 oCtx.lineTo(endX, originY);
65 oCtx.fill();
66
67 // 5.计算Y轴终点的位置
68 let endY = gridSize;
69 // 3.绘制Y轴
70 oCtx.beginPath();
71 oCtx.moveTo(originX, originY);
72 oCtx.lineTo(originX, endY);
73 oCtx.strokeStyle = "#000";
74 oCtx.stroke();
75 // 4.绘制X轴的箭头
76 oCtx.lineTo(originX - 5, endY + 10);
77 oCtx.lineTo(originX + 5, endY + 10);
78 oCtx.lineTo(originX, endY);
79 oCtx.fill();
80
81 // 1.拿到服务器返回数据
82 let list = [
83 {
84 x: 100,
85 y: 300
86 },
87 {
88 x: 200,
89 y: 200
90 },
91 {
92 x: 300,
93 y: 250
94 },
95 ];
96 let data = {
97 x: 100,
98 y: 300
99 }
100 // 2.绘制矩形
101 for(let i = 0; i < list.length; i++){
102 let barHeight = originY - list[i].y;
103 oCtx.fillRect(list[i].x, list[i].y, gridSize, barHeight);
104 }
105
106 </script>
107 </body>
108 </html>