| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113 |
- <template>
- <canvas class="ec-canvas" :id="canvasId" :canvasId="canvasId" @touchstart="touchStart" @touchmove="touchMove"
- @touchend="touchEnd" @error="error"></canvas>
- </template>
- <script>
- import WxCanvas from './wx-canvas';
- import * as echarts from './echarts.esm.min.js';
- export default {
- props: {
- onInit: {
- required: true,
- type: Function,
- default: null
- },
- canvasId: {
- type: String,
- default: 'ec-canvas'
- },
- lazyLoad: {
- type: Boolean,
- default: false
- },
- disableTouch: {
- type: Boolean,
- default: false
- },
- throttleTouch: {
- type: Boolean,
- default: false
- }
- },
- mounted() {
- this.echarts = echarts;
- if (!this.echarts) {
- console.warn('组件需绑定 echarts 变量,例:<ec-canvas id="mychart-dom-bar" ' +
- 'canvas-id="mychart-bar" :echarts="echarts"></ec-canvas>');
- return;
- }
- if (!this.lazyLoad) this.init();
- },
- methods: {
- init() {
- const canvasId = this.canvasId;
- this.ctx = uni.createCanvasContext(canvasId, this);
- const canvas = new WxCanvas(this.ctx, canvasId);
- this.echarts.setCanvasCreator(() => canvas);
- const query = uni.createSelectorQuery().in(this);
- query.select(`#${canvasId}`).boundingClientRect(res => {
- if (!res) {
- setTimeout(() => this.init(), 200);
- return;
- }
- this.chart = this.onInit(canvas, res.width, res.height);
- }).exec();
- },
- canvasToTempFilePath(opt) {
- const { canvasId } = this;
- this.ctx.draw(true, () => {
- uni.canvasToTempFilePath({
- canvasId,
- ...opt
- });
- });
- },
- touchStart(e) {
- const { disableTouch, chart } = this;
- if (disableTouch || !chart || !e.mp.touches.length) return;
- const touch = e.mp.touches[0];
- chart._zr.handler.dispatch('mousedown', {
- zrX: touch.x,
- zrY: touch.y
- });
- chart._zr.handler.dispatch('mousemove', {
- zrX: touch.x,
- zrY: touch.y
- });
- },
- touchMove(e) {
- const { disableTouch, throttleTouch, chart, lastMoveTime } = this;
- if (disableTouch || !chart || !e.mp.touches.length) return;
- if (throttleTouch) {
- const currMoveTime = Date.now();
- if (currMoveTime - lastMoveTime < 240) return;
- this.lastMoveTime = currMoveTime;
- }
- const touch = e.mp.touches[0];
- chart._zr.handler.dispatch('mousemove', {
- zrX: touch.x,
- zrY: touch.y
- });
- },
- touchEnd(e) {
- const { disableTouch, chart } = this;
- if (disableTouch || !chart) return;
- const touch = e.mp.changedTouches ? e.mp.changedTouches[0] : {};
- chart._zr.handler.dispatch('mouseup', {
- zrX: touch.x,
- zrY: touch.y
- });
- chart._zr.handler.dispatch('click', {
- zrX: touch.x,
- zrY: touch.y
- });
- }
- }
- };
- </script>
- <style scoped>
- .ec-canvas {
- width: 750rpx;
- height: 300px;
- }
- </style>
|