bar.vue 2.54 KB
<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>