1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 | class 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 |
|
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 |
|
102 | export default lineChartUtil;
|