vue中echarts的3D饼图实现

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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
<script>
/**
* props: 未列出的props与原Chart组件相同
* height: 高度
* data: 格式化后的数据,不是chart option
* option:同 data,取此名是为方便直接修改2D组件为3D组件而不用修改props字段
* distance: 视角距离,值越大饼图越小,默认200
* position: [left, top] 饼图位置,取值:百分比|数字字符串,默认值['-25%', '0']
* tipField: 饼图鼠标划过百分比取值字段,默认 rate || LZ
* legendPosition: [left, top] legend位置,取值:百分比|数字字符串,默认 ['50%', 'height/5.5']
* legendRich: legend rich,默认值请在下面代码中查看
* legendFormatter(name, data): legend formatter,data即格式化后的数据,默认值请在下面代码中查看
* autoRotate: 自动旋转, 默认 false
*/

import isEqual from 'lodash/isEqual'
import isEmpty from 'lodash/isEmpty'
import find from 'lodash/find'
import colors from '@/comp/colors'

function fixedUnit(num = 0) {
if (isNaN(num)) num = 0
num = Math.abs(num)
if (num > 1e4) {
return '万'
}

return ''
}
function fixed4(num) {
if (isNaN(num) || num == null) return '-'
let flag = false
if (num < 0) {
num = Math.abs(num)
flag = true
}
if (num > 1e4) {
num = parseInt(num / 1e2) / 100
}
return ((flag ? '-' : '') + num) * 1
}

function getParametricEquation(startRatio, endRatio, isSelected, isHovered, k, height) {
// 计算
const midRatio = (startRatio + endRatio) / 2
const startRadian = startRatio * Math.PI * 2
const endRadian = endRatio * Math.PI * 2
const midRadian = midRatio * Math.PI * 2

// 如果只有一个扇形,则不实现选中效果。
if (startRatio === 0 && endRatio === 1) {
isSelected = false
}

// 通过扇形内径/外径的值,换算出辅助参数 k(默认值 1/3)
k = k ?? 1 / 3

// 计算选中效果分别在 x 轴、y 轴方向上的位移(未选中,则位移均为 0)
const offsetX = isSelected ? Math.cos(midRadian) * 0.1 : 0
const offsetY = isSelected ? Math.sin(midRadian) * 0.1 : 0

// 计算高亮效果的放大比例(未高亮,则比例为 1)
const hoverRate = isHovered ? 1.1 : 1

// 返回曲面参数方程
return {
u: {
min: -Math.PI,
max: Math.PI * 3,
step: Math.PI / 32,
},

v: {
min: 0,
max: Math.PI * 2,
step: Math.PI / 20,
},

x: function (u, v) {
if (u < startRadian) {
return offsetX + Math.cos(startRadian) * (1 + Math.cos(v) * k) * hoverRate
}
if (u > endRadian) {
return offsetX + Math.cos(endRadian) * (1 + Math.cos(v) * k) * hoverRate
}
return offsetX + Math.cos(u) * (1 + Math.cos(v) * k) * hoverRate
},

y: function (u, v) {
if (u < startRadian) {
return offsetY + Math.sin(startRadian) * (1 + Math.cos(v) * k) * hoverRate
}
if (u > endRadian) {
return offsetY + Math.sin(endRadian) * (1 + Math.cos(v) * k) * hoverRate
}
return offsetY + Math.sin(u) * (1 + Math.cos(v) * k) * hoverRate
},

z: function (u, v) {
if (u < -Math.PI * 0.5) {
return Math.sin(u)
}
if (u > Math.PI * 2.5) {
return Math.sin(u)
}
return Math.sin(v) > 0 ? 1 * height : -1
},
}
}

// 生成模拟 3D 饼图的配置项
function getPie3D({
pieData,
tipField,
position,
legendPosition,
legendRich,
legendFormatter,
autoRotate,
boxHeight,
distance,
internalDiameterRatio,
}) {
const series = []
let sumValue = 0
let startValue = 0
let endValue = 0
const legendData = []
const k =
typeof internalDiameterRatio !== 'undefined' ? (1 - internalDiameterRatio) / (1 + internalDiameterRatio) : 1 / 3

// 为每一个饼图数据,生成一个 series-surface 配置
for (let i = 0; i < pieData.length; i++) {
sumValue += pieData[i].value * 1

const seriesItem = {
name: pieData[i].name ?? `series${i}`,
type: 'surface',
parametric: true,
wireframe: {
show: false,
},
pieData: pieData[i],
pieStatus: {
selected: false,
hovered: false,
k,
},
}

if (!pieData[i].itemStyle) {
const itemStyle = {}

if (!pieData[i].itemStyle.color) {
itemStyle.color = pieData[i].itemStyle.color
} else {
itemStyle.color = colors[i]
}
if (!pieData[i].itemStyle.opacity) {
itemStyle.opacity = pieData[i].itemStyle.opacity
} else {
itemStyle.opacity = 1
}

seriesItem.itemStyle = itemStyle
}
series.push(seriesItem)
}
// 使用上一次遍历时,计算出的数据和 sumValue,调用 getParametricEquation 函数,
// 向每个 series-surface 传入不同的参数方程 series-surface.parametricEquation,也就是实现每一个扇形。
const isZero = pieData.every((e) => e.value * 1 === 0)
const len = series.length || 1
for (let i = 0; i < len; i++) {
if (!series[i]?.pieData) series[i].pieData = {}
if (isZero) {
series[i].pieData.startRatio = i / len
series[i].pieData.endRatio = i === len - 1 ? 1 : (i + 1) / len
} else {
endValue = startValue * 1 + (series[i]?.pieData.value || 0) * 1
series[i].pieData.startRatio = startValue / sumValue
series[i].pieData.endRatio = i === len - 1 ? 1 : endValue / sumValue
}
series[i].parametricEquation = getParametricEquation(
series[i].pieData.startRatio,
series[i].pieData.endRatio,
false,
false,
k,
4000
)

startValue = endValue

legendData.push(series[i].name)
}

// series.push({
// name: 'pie2d',
// type: 'pie',
// label: {
// opacity: 1,
// position: 'outside',
// fontSize: 12,
// lineHeight: 20,
// textStyle: {
// fontSize: 12,
// color: '#fff',
// },
// },
// labelLine: {
// length: 30,
// length2: 30,
// },
// minAngle: 10,
// startAngle: 50, // 起始角度,支持范围[0, 360]。
// clockwise: false, // 饼图的扇区是否是顺时针排布。上述这两项配置主要是为了对齐3d的样式
// radius: ['60%', '60%'],
// center: ['30%', '50%'],
// data: pieData.map((item) => {
// item.itemStyle.opacity = 0
// return item
// }),
// })

// 准备待返回的配置项,把准备好的 legendData、series 传入。
const option = {
animation: true,
color: colors,
backgroundColor: 'rgba(0,0,0,0)',
// 图例组件
legend: {
data: legendData,
// 图例列表的布局朝向。
orient: 'vertical',
left: legendPosition[0] ?? '50%',
top: legendPosition[1] ?? boxHeight / 5.5,
// 图例文字每项之间的间隔
itemGap: 5,
show: true,
icon: 'rect',
itemHeight: 10,
itemWidth: 10,
textStyle: {
// 图例字体大小
fontSize: 12,
color: '#B8DDFF',
lineHeight: 14,
rich: legendRich,
},

// 格式化图例文本
formatter: function (name) {
return legendFormatter(name, pieData)
},
},

tooltip: {
formatter: (params) => {
if (params.seriesName !== 'mouseoutSeries' && params.seriesName !== 'pie2d') {
const item = option.series[params.seriesIndex]?.pieData || {}
const rate = item[tipField] ?? item?.rate ?? item?.LZ ?? '-'
return `${
params.seriesName
}<br/><span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${
params.color
};"></span>${rate + '%'}`
}
},
textStyle: {
fontSize: 14,
},
},
title: {
x: 'center',
top: '20',
textStyle: {
color: '#fff',
fontSize: 22,
},
},

labelLine: {
show: true,
lineStyle: {
color: '#7BC0CB',
},
normal: {
show: true,
length: 10,
length2: 10,
},
},
label: {
show: true,
position: 'outside',
formatter: '{b} \n{d}%',
textStyle: {
color: '#fff',
fontSize: '12px',
},
},
xAxis3D: {
min: -1,
max: 1,
},
yAxis3D: {
min: -1,
max: 1,
},
zAxis3D: {
min: -1,
max: 1,
},
grid3D: {
show: false,
boxHeight: 0.01,
left: position[0] ?? '-25%',
top: position[1] ?? '0',
// environment: 'rgba(0,0,0,0)',
viewControl: {
distance,
alpha: 35,
beta: 60,
autoRotate, // 自动旋转
zoomSensitivity: false,
rotateSensitivity: false,
},
},
series: series,
}

return option
}

function bindListen(
chart,
data,
distance,
position,
tipField,
legendPosition,
legendRich,
legendFormatter,
autoRotate,
boxHeight
) {
chart.setOption(
getPie3D({
pieData: data,
tipField,
position,
legendPosition,
legendRich,
legendFormatter,
autoRotate,
boxHeight,
distance,
internalDiameterRatio: 0.6,
})
)
}

export default {
props: {
reset: {
type: Boolean,
default: true,
},
height: {
type: Number,
default: 400,
},
option: {
type: Array,
default: () => [],
},
data: {
type: Array,
default: () => [],
},
distance: {
type: [Number, String],
default: 200,
},
position: {
type: Array,
default: () => [],
},
tipField: {
type: String,
default: '',
},
legendPosition: {
type: Array,
default: () => [],
},
legendRich: {
type: Object,
default: () => ({
one: {
color: '#ffffff',
width: 60,
},
two: {
color: '#59caf0',
fontSize: 18,
fontWeight: 600,
},
three: {
color: '#d7dcf2',
},
}),
},
legendFormatter: {
type: Function,
default: (name, pieData) => {
const item = find(pieData, ['name', name])
return `{one|${name}} {two|${fixed4(item.value)}} {three|${fixedUnit(item.value)}个}`
},
},
autoRotate: {
type: Boolean,
default: false,
},
},
data() {
return {
chart: null,
}
},
computed: {
list() {
if (!isEmpty(this.option)) return this.option
else if (!isEmpty(this.data)) return this.data

return []
},
},
watch: {
list(n, o) {
if (!isEqual(n, o)) {
if (this.reset) {
this.chart.clear()
}
bindListen(
this.chart,
n,
this.distance * 1,
this.position,
this.tipField,
this.legendPosition,
this.legendRich,
this.legendFormatter,
this.autoRotate,
this.height
)
}
},
},
mounted() {
this.initChart()
},
methods: {
resize() {
this.chart.resize()
},
clear() {
const canvasArr = this.chart.getDom().getElementsByTagName('canvas')
for (const item of canvasArr) {
const itemWebgl = item.getContext('webgl')
itemWebgl?.getExtension && itemWebgl.getExtension('WEBGL_lose_context').loseContext()
}
this.chart.clear()
},
initChart() {
this.chart = this.$echarts.init(this.$refs.chart)
this.chart.resize()
window.addEventListener('resize', () => {
this.chart.resize()
})
bindListen(
this.chart,
this.list,
this.distance * 1,
this.position,
this.tipField,
this.legendPosition,
this.legendRich,
this.legendFormatter,
this.autoRotate,
this.height
)
this.chart.off('legendselectchanged')
this.chart.on('legendselectchanged', (p) => {
this.chart.setOption({
legend: { selected: { [p.name]: true } },
})
if (this.$listeners['legend']) {
this.$emit('legend', p)
}
})
},
},
}
</script>
<template>
<div ref="chart" :style="{ width: '100%', height: height <= 100 ? `${height}%` : `${height}px` }"></div>
</template>