f2.vue 2.24 KB
<template>
  <canvas
    :id="`f2-canvas-${$id}`"
    :canvas-id="`f2-canvas-${$id}`"
    class="f2-canvas"
    :width="canvasWidth"
    :height="canvasHeight"
    @touch-start="touchStart"
    @touch-move="touchMove"
    @touch-end="touchEnd"
  />
</template>

<script>
import F2 from '@antv/f2';
import { my as my$1 } from '@antv/f2-context';

function wrapEvent(e) {
  if (!e) return;
  if (!e.preventDefault) {
    e.preventDefault = function() {};
  }
  return e;
}

export default {
  props: {
    init: {
      type: Function,
      default: () => {}
    },
    width: Number,
    height: Number,
  },
  data: function() {
    return {
      canvasEl: null,
      canvasWidth: this.width,
      canvasHeight: this.height,
    };
  },
  mounted: function() {
    const id = `f2-canvas-${this.$id}`;
    const myCtx = uni.createCanvasContext(id, this);
    const context = my$1(myCtx);
    const query = uni.createSelectorQuery().in(this);
    query
      .select(`#${id}`)
      .boundingClientRect()
      .exec(res => {
        // 获取画布实际宽高, 用props的宽高做失败兜底
        const { width, height } = res && res[0] ? res[0] : this;
        if (!width || !height) {
          return;
        }
        const pixelRatio = uni.getSystemInfoSync().pixelRatio;
        const ref = this;
        this.canvasWidth = width * pixelRatio;
        this.canvasHeight = height * pixelRatio;
        this.$nextTick(() => {
          // 高清解决方案
          const chart = this.init(F2, { context, width, height, pixelRatio }, ref);
          if (chart) {
            this.canvasEl = chart.get('el');
          }
        });
      });
  },
  methods: {
    touchStart: function(e) {
      const canvasEl = this.canvasEl;
      if (!canvasEl) {
        return;
      }
      canvasEl.dispatchEvent('touchstart', wrapEvent(e));
    },
    touchMove: function(e) {
      const canvasEl = this.canvasEl;
      if (!canvasEl) {
        return;
      }
      canvasEl.dispatchEvent('touchmove', wrapEvent(e));
    },
    touchEnd: function(e) {
      const canvasEl = this.canvasEl;
      if (!canvasEl) {
        return;
      }
      canvasEl.dispatchEvent('touchend', wrapEvent(e));
    }
  }
}
</script>

<style>
.f2-canvas {
  width: 100%;
  height: 100%;
}
</style>