DrawPie.js
3.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
const _ctx_ = Symbol('_ctx_')
const _pixelRatio_ = Symbol('_pixelRatio_')
const _canvas_ = Symbol('_canvas_')
const _params_ = Symbol('_params_')
const PI = Math.PI
class DrawPieChart {
[_ctx_] = null;
[_pixelRatio_] = null;
[_canvas_] = null;
[_params_] = null;
arcInfo = null;
constructor(el, params, componentsThis) {
const query = wx.createSelectorQuery().in(componentsThis)
query.select(el).fields({
node: true,
size: true
}).exec((res) => {
const canvas = res[0].node,
ctx = canvas.getContext('2d'),
dpr = wx.getSystemInfoSync().pixelRatio,
width = res[0].width * dpr,
height = res[0].height * dpr
canvas.width = width
canvas.height = height
this[_canvas_] = canvas
this[_ctx_] = ctx
this[_pixelRatio_] = dpr
this[_params_] = params
this[_ctx_].clearRect(0, 0, width, height)
this.arcInfo = {
x: width / 2,
y: width / 2,
innerRadius: this.toRpx(40),
outerRadius: this.toRpx(60),
lineWidth: this.toRpx(20),
arcRadius: this.toRpx(50)
}
this.drawBackground(params)
})
}
drawBackground(params) {
const {
x,
y,
innerRadius,
outerRadius
} = this.arcInfo
this[_ctx_].beginPath()
this[_ctx_].arc(x, y, innerRadius, 0, 2 * PI)
this[_ctx_].arc(x, y, outerRadius, 0, 2 * PI, true)
this[_ctx_].fillStyle = '#fff'
this[_ctx_].fill()
this[_ctx_].save()
const {
data,
colorList
} = params,
totalSum = data.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
this.drawArc({
data,
colorList
}, totalSum, 0, PI * 1.5)
}
drawArc({
data,
colorList
}, totalSum, index = 0, startAngle) {
const {
x,
y,
lineWidth,
arcRadius
} = this.arcInfo,
gapAngle = data.length == 1 ? 0 : Math.PI / 300
let endAngle = startAngle + (Math.PI * 2 * (data[index] / totalSum)) - gapAngle;
this[_ctx_].beginPath()
this[_ctx_].strokeStyle = colorList[index]
this[_ctx_].lineWidth = lineWidth
this[_ctx_].arc(x, y, arcRadius, startAngle + gapAngle, endAngle)
this[_ctx_].stroke()
this[_ctx_].save()
// 计算扇形中心的角度和坐标
const centerAngle = (startAngle + endAngle) / 2,
textX = x + arcRadius * Math.cos(centerAngle),
textY = y + arcRadius * Math.sin(centerAngle)
// 设置文本样式
const [, font] = this[_ctx_].font.split('px')
this[_ctx_].textBaseline = 'middle';
this[_ctx_].textAlign = 'center';
this[_ctx_].font = `400 ${this.toRpx(14)}px ${font}`
this[_ctx_].fillStyle = '#fff';
// 绘制文本
this[_ctx_].fillText(data[index]?.toString() || '', textX, textY);
index += 1
if (index < data.length) {
this[_canvas_].requestAnimationFrame(() => {
this.drawArc({
data,
colorList
}, totalSum, index, endAngle + gapAngle)
})
}
}
toRpx(val) {
return this[_pixelRatio_] * val
}
}
export default DrawPieChart