UNPKG

2.62 kBJavaScriptView Raw
1/**
2* @description 折线图绘制
3* @author SoldierAb
4* @param {Object} cx 画布实例
5* @param {Array} renderData 绘制数据
6* @param {Number} cxH 画布高度
7* @param {Number} cxW 画布宽度
8* @param {Number} lineWidth 线条宽度
9* @param {String} strokeStyle 线条颜色
10* @param {String} backgroundStyle 背景颜色
11* @param {String} fillStyle 填充颜色
12* @param {Number} splitLen 分割份数
13* @example
14* const lineInstance=new lineChartUtil(ParamObj);
15* lineInstance.render();
16*/
17
18
19class lineChartUtil{
20 constructor({cx,renderData,cxH,cxW,lineWidth,strokeStyle,backgroundStyle,fillStyle,splitLen}){
21 this.cx=cx;
22 this.cxH=cxH;
23 this.cxW=cxW;
24 this.splitLen=splitLen;
25 this.lineWidth=lineWidth;
26 this.fillStyle=fillStyle;
27 this.strokeStyle=strokeStyle;
28 this.backgroundStyle=backgroundStyle;
29 this.renderData=renderData;
30 // console.log(this.renderData);
31 }
32
33 render(){
34 let {cx,lineWidth,strokeStyle,renderData,cxH,cxW,backgroundStyle,splitLen,fillStyle}=this;
35 this.clear();
36 if(!renderData) throw new Error('renderData is required!');
37 //面板背景绘制
38 if(backgroundStyle) this.drawBg(cx,[0,0],cxW,cxH,backgroundStyle);
39
40 //坐标轴绘制
41 if(splitLen){
42 for(let i=1;i<splitLen;i++){
43 this.drawLine(cx,[0,i*cxH/splitLen],[cxW,i*cxH/splitLen - 2],0.2,strokeStyle);
44 }
45 }
46
47 //过程线绘制
48 for(let i=0;i<renderData.length-1;i++){
49 this.drawLine(cx,renderData[i],renderData[i+1],lineWidth,strokeStyle);
50 }
51
52 //折线填充颜色
53 if(fillStyle) this.fillBg(cx,[0,cxH],[cxW,cxH],renderData,fillStyle,strokeStyle,lineWidth);
54 }
55
56 clear(){
57 let {cx,cxW,cxH}=this;
58 cx&&cx.clearRect(0,0,cxW,cxH);
59 }
60
61 fillBg(cx,startPos,endPos,renderData,fillStyle){
62 cx.fillStyle=fillStyle;
63 cx.beginPath();
64 cx.moveTo(...startPos);
65 for(let i=0;i<renderData.length;i++){
66 cx.lineTo(...renderData[i]);
67 }
68 cx.lineTo(...endPos);
69 cx.closePath();
70 cx.fill();
71 cx.save();
72 }
73
74 drawLine(cx,startPos,endPos,lineWidth,strokeStyle){
75 cx.lineWidth=lineWidth;
76 cx.strokeStyle=strokeStyle;
77 cx.beginPath();
78 cx.moveTo(...startPos);
79 cx.lineTo(...endPos);
80 cx.stroke();
81 cx.closePath();
82 cx.save();
83 }
84
85 drawBg(cx,startPos,cxW,cxH,fillStyle){
86 cx.fillStyle=fillStyle;
87 cx.beginPath();
88 cx.moveTo(...startPos);
89 cx.rect(...startPos,cxW,cxH);
90 cx.fill();
91 cx.closePath();
92 cx.save();
93 }
94
95 resize(){
96 let {cx,cxH,cxW}=this;
97 cx.clearRect(0,0,cxW,cxH);
98 this.render();
99 }
100}
101
102export default lineChartUtil;