This article mainly introduces how to introduce Echarts from native applets. At the end of the article, we will give the warehouse address of native applets into Echarts and the warehouse address of uniApp into Echarts.

Step 1: Introduce Echarts

In normal cases, such as on the Web side, the direct approach is NPM install echarts –save. However, if you install it directly in a small program, it will lead to the problem that the compiled code package is too large. Therefore, we can use the compressed version of Echart, echart.min.js. Place this file in the EC-canvas folder. Or go to the warehouse address at the end of the article to check.

Step 2: Implement the Canvas component

  1. Ec-canvas.js It is worth mentioning that the data used to draw the chart is usually returned by the server, so the lazyLoad attribute defaults to true, meaning that the chart is initialized when the data is received.

We’ll notice that this file introduces a WxCanvas, which is a wrapper tool for drawing canvas.

// ec-canvas.js
import WxCanvas from './wx-canvas';
import * as echarts from './echart';
let ctx;

Component({
  properties: {
    canvasId: {
      type: String.value: 'ec-canvas'
    },
    lazyLoad: {
      type: Boolean.value: false
    },
    disableTouch: {
      type: Boolean.value: false
    },
    throttleTouch: {
      type: Boolean.value: false}},ready: function() {
    if (!this.lazyLoad) this.init();
  },
  methods: {
    init: function (callback) {
      ctx = wx.createCanvasContext(this.data.canvasId, this);

      const canvas = new WxCanvas(ctx, this.data.canvasId);

      echarts.setCanvasCreator((a)= > {
        return canvas;
      });

      var query = wx.createSelectorQuery().in(this);
      query.select('.ec-canvas').boundingClientRect(res= > {
        if (typeof callback === 'function') {
          this.chart = callback(canvas, res.width, res.height);
        }
        else if (this.data.ec && typeof this.data.ec.onInit === 'function') {
          this.chart = this.data.ec.onInit(canvas, res.width, res.height);
        }
        else {
          this.triggerEvent('onInit', {
            canvas: canvas,
            width: res.width,
            height: res.height
          });
        }
      }).exec();
    },

    canvasToTempFilePath(opt) {
      if(! opt.canvasId) { opt.canvasId =this.data.canvasId;
      }

      ctx.draw(true, () => {
        wx.canvasToTempFilePath(opt, this);
      });
    },

    touchStart(e) {
      if (this.chart && e.touches.length > 0) {
        var touch = e.touches[0];
        var handler = this.chart.getZr().handler;
        handler.dispatch('mousedown', {
          zrX: touch.x,
          zrY: touch.y
        });
        handler.dispatch('mousemove', {
          zrX: touch.x,
          zrY: touch.y
        });
        handler.processGesture(wrapTouch(e), 'start');
      }
    },

    touchMove(e) {
      if (this.chart && e.touches.length > 0) {
        var touch = e.touches[0];
        var handler = this.chart.getZr().handler;
        handler.dispatch('mousemove', {
          zrX: touch.x,
          zrY: touch.y
        });
        handler.processGesture(wrapTouch(e), 'change');
      }
    },

    touchEnd(e) {
      if (this.chart) {
        const touch = e.changedTouches ? e.changedTouches[0] : {};
        var handler = this.chart.getZr().handler;
        handler.dispatch('mouseup', {
          zrX: touch.x,
          zrY: touch.y
        });
        handler.dispatch('click', {
          zrX: touch.x,
          zrY: touch.y
        });
        handler.processGesture(wrapTouch(e), 'end'); }}}})Copy the code
// wx-canvas.js
export default class WxCanvas {
  constructor(ctx, canvasId) {
    this.ctx = ctx;
    this.canvasId = canvasId;
    this.chart = null;

    WxCanvas.initStyle(ctx);
    this.initEvent();
  }

  getContext(contextType) {
    return contextType === '2d' ? this.ctx : null;
  }

  setChart(chart) {
    this.chart = chart;
  }

  attachEvent () {
    // noop
  }

  detachEvent() {
    // noop
  }

  static initStyle(ctx) {
    const styles = [
      'fillStyle'.'strokeStyle'.'globalAlpha'.'textAlign'.'textBaseAlign'.'shadow'.'lineWidth'.'lineCap'.'lineJoin'.'lineDash'.'miterLimit'.'fontSize'
    ]

    styles.forEach((style) = > {
      Object.defineProperty(ctx, style, {
        set: (value) = > {
          if((style ! = ='fillStyle'&& style ! = ='strokeStyle') || (value ! = ='none'&& value ! = =null)
          ) {
            ctx[`set${style.charAt(0).toUpperCase()}${style.slice(1)}`](value); }}}); }); ctx.createRadialGradient =(a)= > ctx.createCircularGradient(arguments);
  }

  initEvent() {
    this.event = {};
    const eventNames = [{
      wxName: 'touchStart'.ecName: 'mousedown'}, {wxName: 'touchMove'.ecName: 'mousemove'}, {wxName: 'touchEnd'.ecName: 'mouseup'}, {wxName: 'touchEnd'.ecName: 'click',}]; eventNames.forEach((name) = > {
      this.event[name.wxName] = (e) = > {
        const touch = e.mp.touches[0];
        this.chart._zr.handler.dispatch(name.ecName, {
          zrX: name.wxName === 'tap' ? touch.clientX : touch.x,
          zrY: name.wxName === 'tap'? touch.clientY : touch.y, }); }; }); }}Copy the code
  1. ec-canvas.wxml
<block wx:if="{{ canvasId }}">
  <canvas
    class="ec-canvas"
    id="{{ canvasId }}"
    canvasId="{{ canvasId }}"
    bindtouchstart="touchStart"
    bindtouchmove="touchMove"
    bindtouchend="touchEnd"
    binderror="error"
  ></canvas>
</block>
Copy the code
  1. Ec – canvas. Json and ec – canvas. WXSS
{
  "component": true."usingComponents": {}}Copy the code
.ec-canvas {
  width: 100%;
  height: 100%;
  flex: 1;
}
Copy the code

Step 3: Introduce the Chart component into the page

  1. index.js
// index.js
import * as echarts from '.. /.. /ec-canvas/echart';

Page({
  data: {},onLoad: function () {
    this.initChart()
  },

  // Initialize the chart
  initChart() {
    const chartComponent = this.selectComponent('#chart')
    chartComponent.init((canvas, width, height) = > {
      const chart = echarts.init(canvas, null, {
        width,
        height
      })
      
      const option = {
        tooltip: {
          trigger: 'axis'.axisPointer: {
            type: 'shadow'}},legend: {
          orient: 'vertical'.x: 'right'.data: ['Billing amount'].textStyle: {
            fontSize: 12.color: '# 999999'}},grid: {
          left: '2%'.right: '5%'.bottom: '5%'.top: "15%".containLabel: true
        },
        color: ['#87E7FF'].xAxis: {
          type: 'category'.data: ['2020-07-18'.'2020-07-19'.'2020-07-20'.'2020-07-21'.'2020-07-22'.'2020-07-23'.'2020-07-24'].axisLabel: {
            textStyle: {
              fontSize: 12.color: '# 999999'}},axisTick: {
            alignWithLabel: true}},yAxis: {
          type: 'value'.axisTick: {
            inside: true
          },
          scale: true.axisLabel: {
            textStyle: {
              fontSize: 12.color: '# 999999'
            },
            margin: 5.formatter: function (value) {
              if (value >= 1000) {
                value = value / 1000 + "k";
              }
      
              returnvalue; }}},series: [{
          name: 'value'.stack: The '-'.type: 'bar'.data: [ 572011.2204.44337.62701.106909.44410.146850].value: [ 572011.2204.44337.62701.106909.44410.146850]]}}; chart.setOption(option)return chart
    })
  }
})
Copy the code
  1. index.wxml
<view class="container">
  <view class="ec">
    <ec-canvas id="chart" lazyLoad="{{ true }}"></ec-canvas>
  </view>
</view>
Copy the code

The last step

If there is no chart on the page and no error on the console, you have probably forgotten a key step: add the parent element to the EC-Canvas component and set the width and height.

.ec {
  margin-top: 40rpx;
  width: 100%;
  height: 400rpx;
}
Copy the code

The introduction of Echarts in Uniapp is very similar to native, and the implementation principle is the same. You can pick it up from the warehouse if you need it.

Warehouse address: native applet: github.com/zpf0918/ech…

Uniapp: github.com/zpf0918/ech…

Reference: www.jianshu.com/p/5537e5053…

< About us >

We are one front-end programmer monkey + one front-end programmer girl from the imperial capital.

The articles posted here are a summary of what we have learned and are expected to be updated at least once a week.

At present our learning plan is: small program actual combat => VUE advanced usage => VUE principle => CSS foundation => ES6 => JS in-depth

In addition, some of the technologies and functions used in the work will be summarized and updated here in time

If the article is wrong or not clear, welcome to leave a message feedback ~~