bar.vue
2.54 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
112
<template>
<div class="bar-container">
<canvas class="canvas" :id="refId"></canvas>
</div>
</template>
<script>
import F2 from '@antv/f2/lib/index-all'
export default {
name: 'barChart',
data() {
return {
chart: null,
chartColor: this.color,
refId: this.id,
barList: this.list
}
},
props: {
color: {
type: String,
default: ''
},
list: {
type: Array,
default: () => []
},
id: {
type: String,
default: () => ''
},
tickCount: {
type: Number,
default: () => 5
}
},
mounted() {
this.initCanvas()
},
watch: {
list() {
this.initCanvas()
}
},
methods: {
initCanvas() {
let id = this.refId
let { barList, color } = this
let tickIntervalNum = 0
// 判断barList是否有值,根据barList中最大值计算tickInterval
if (barList.length) {
let s = barList[0].value
for (var i = 1; i < barList.length; i++) {
if (s < barList[i].value) {
s = barList[i].value
}
}
tickIntervalNum = s
}
let textLength = 2
this.list.forEach(item => {
textLength = item.text.length > textLength ? item.text.length : textLength
})
this.chart && this.chart.clear()
this.chart = null
this.chart = new F2.Chart({
id,
pixelRatio: window.devicePixelRatio,
padding: [16, 24, 24, textLength * 10 + 20],
height: barList.length < 2 ? 80 : barList.length * 45
})
this.chart.source(barList, {
value: {
tickCount: this.tickCount,
tickInterval: Math.ceil(tickIntervalNum / this.tickCount)
}
})
this.chart.coord({
transposed: true
})
this.chart.interval().position('text*value').color(color).style({
height: 16,
})
this.chart.render()
// 绘制柱状图文本
const offset = -5
const canvas = this.chart.get('canvas')
const group = canvas.addGroup()
const shapes = {}
barList.forEach(obj => {
const point = this.chart.getPosition(obj)
const text = group.addShape('text', {
attrs: {
x: textLength * 10 + 30,
y: point.y - offset,
text: obj.value,
fill: '#ffffff',
fontSize: 10
}
})
shapes[obj.text] = text // 缓存该 shape, 便于后续查找
})
}
}
}
</script>
<style lang="scss" scoped>
.canvas {
width: 100%;
// height: 160px;
}
</style>