用canvas绘制折线图

Posted !master

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用canvas绘制折线图相关的知识,希望对你有一定的参考价值。

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>用canvas绘制折线图</title>
 6 </head>
 7 <body>
 8     <canvas id="cv"></canvas>
 9 </body>
10 </html>
11 <script>
12     var cv = document.getElementById("cv");
13     cv.width = 600;
14     cv.height = 400;
15     cv.style.border = "1px solid red";
16     var ctx = cv.getContext("2d");
17     var data2 = [.3, .1, .2, .4, .2, .7, .3, .9];
18     var data3 = [3, 12, 14, 17, 29, 33, 40, 52];
19 
20     getBrokenLine(data2, "#f00");
21     getBrokenLine(data3, "#0f0");
22 
23     //封装一个折线图的函数
24     function getBrokenLine(data, color) {
25         var maxNum = Math.max.apply(null, data);    //求数组中的最大值
26         var padding = 20,  //边距
27                 x0 = padding,  //原点x轴坐标
28                 y0 = cv.height - padding,  //原点y轴坐标
29                 xArrow_x = padding, //x轴箭头处坐标x
30                 xArrow_y = padding, //x轴箭头处坐标y
31                 yArrow_x = cv.width - padding,  //y轴箭头处坐标x
32                 yArrow_y = cv.height - padding, //y轴箭头处坐标y
33                 arrowWidth = 10,    //箭头的宽度
34                 xLength = cv.width - 2*padding - arrowWidth,    //x轴的长度
35                 yLength = cv.height - 2*padding - arrowWidth,  //y轴的长度
36                 pointsWidth = xLength/(data.length + 1);    //折线上每个点之间的距离
37 
38         ctx.beginPath();//控制绘制的折线不受坐标轴样式属性的影响
39         //绘制x轴
40         ctx.moveTo(x0, y0);
41         ctx.lineTo(xArrow_x, xArrow_y);
42         ctx.moveTo(xArrow_x, xArrow_y);
43         ctx.lineTo(xArrow_x - arrowWidth, xArrow_y + arrowWidth);
44         ctx.moveTo(xArrow_x, xArrow_y);
45         ctx.lineTo(xArrow_x + arrowWidth, xArrow_y + arrowWidth);
46 
47         //绘制y轴
48         ctx.moveTo(x0, y0);
49         ctx.lineTo(yArrow_x, yArrow_y);
50         ctx.moveTo(yArrow_x, yArrow_y);
51         ctx.lineTo(yArrow_x - arrowWidth, yArrow_y - arrowWidth);
52         ctx.moveTo(yArrow_x, yArrow_y);
53         ctx.lineTo(yArrow_x - arrowWidth, yArrow_y + arrowWidth);
54         ctx.strokeStyle = "#000";
55 
56         //中断(坐标轴和折线的)连接
57         ctx.stroke();
58         ctx.beginPath();
59 
60         //绘制折线
61         for (var i = 0; i < data.length; i++) {
62             var pointX = padding + (i + 1) * pointsWidth;
63             var pointY = padding + arrowWidth + (1 - data[i]/maxNum) * yLength;
64             ctx.lineTo(pointX, pointY);
65         }
66         ctx.strokeStyle = color;
67         ctx.stroke();
68     }
69 </script>

效果图如下:

以上是关于用canvas绘制折线图的主要内容,如果未能解决你的问题,请参考以下文章

canvas绘制折线图(仿echarts)

Android自定义组件系列——Canvas绘制折线图

11-canvas绘制折线图

Canvas如何用Canvas绘制折线图

canvas图表详解系列:折线图

canvas学习之折线图