Echarts provides a small version of echarts-for-weixin, encapsulated as a custom component called ec-Canvas for us to refer to directly.

The following will first introduce the echarts features, etc., do not need to jump directly to the small program to use the section.

features

  • Support for online customization, checking desired ICONS and components instead of downloading the entire package.
  • V5.0.1 began to support import on demand.
  • Provides a type interface to facilitate type checking for items that use TS.
  • Echarts includes the default theme, dark and light theme colors, as well as the ability to download and edit more colors in the theme editor.
  • Custom chart style: including configuration palette, throughitemStyle/lineStyleSuch as fine configuration, mouse hover highlight, etc.

Features not supported in the applet version:

  • NPM installation mode, need to be the whole/ec-canvasDirectories are placed in places like/componentsdirectory
  • Import on demand. Only online customization is supported. Customized packages are replaced/ec-canvas/echarts.js
  • chartInstance.showLoading()andchartInstance.hideLoading()Does not support
  • How to use the theme color

An overview of the concept

  • component

The content on Echarts is abstracted into components, including Axes, Legend, Series, Tooltip, Toolbox, and so on. Option Each attribute is a class component.

  • series

Represents a set of data and the map it maps to. At least include parameters for the icon type, data configuration items, and how to map.

(Note: the ith X-axis point should map the ith data of each item in the series as the Y-axis data, which is equivalent to traversing the ith data of the item in the series, and the relationship between the x-coordinate and the y-coordinate is one-to-many).

use

  • The introduction of

Download source code compilation or compiled output, NPM installation, and online customization.

  • Create a chart

Provide a container node with width and height, initialized, and then pass option to represent the diagram.

  • Asynchronous data loading and updating

After obtaining the data, use setOption to fill in the data and configuration items.

As for data processing, Echarts provides both a way to pass data into a series separately and a way to manage data in a dataset attribute. The latter is recommended. A. Manage data and other configuration items separately to improve maintenance. B. It can also be used for reuse; C. Support two-dimensional arrays and object arrays to reduce data format conversion.

The default series maps to the Y-axis. SeriesLayoutBy: series[I].seriesLayoutby: series[I].seriesLayoutby: series[I].seriesLayoutby: series[I].seriesLayoutby

Small program used in

The official document, Echarts-for-weixin, describes in more detail how to use Echarts in small programs. Without going too far into the basics, I’ll just list some scenarios you might encounter in a real project.

Reduce the packet size

The entire EC-Canvas folder is nearly 1M, which is still relatively large. It is suggested to organize visual pages in subcontracting. Also, to consider the need for online customization of the chart, download the file instead of ec-Canvas /echarts.js.

Since I only used bar charts and line charts in my project, with coordinate system, toolTip and other tools, the compressed code was reduced to more than 500K.

Lazy loading chart

Usually the chart data is obtained through asynchronous requests, so you want to initialize the chart after the data is obtained, otherwise you will start with an ugly graph with only axes.

If the page is initialized as soon as it comes in, the official example is given:

<view class="container">
  <ec-canvas id="mychart-dom-bar" canvas-id="mychart-bar" ec="{{ ec }}"></ec-canvas>
</view>
Copy the code
function initChart(canvas, width, height, dpr) {
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr / / pixel
  });
  canvas.setChart(chart);

  var option = {
    ...
  };
  chart.setOption(option);
  return chart;
}

Page({
  data: {
    ec: {
      onInit: initChart
    }
  }
});
Copy the code

You need to provide an object in dataOption with an onInit property whose value is the initialized method.

Since this cannot be accessed at this point, initChart needs to be defined outside of the Page. The problem is that if you want to access the Chart instance later, you need to provide a variable other than the page to receive, which is globally present. If packaged directly as a small program custom component, the Chart instance variable requires a little extra reuse.

Take another look at the lazy loading diagram:

Page({
    data: {
        ec: {
            lazyLoad: true}},onReady: function () {
        // Manually retrieve the echart node
        this.compBar = this.selectComponent('#mychart-dom-bar')
        this.loadData()
    },
    loadData: function() {
        api.getData().then(res= > {
            // Update configuration items such as data
            const opts = {
              dataset: {
                dimensions: res.dimensions,
                source: res.source
              }
            }
            
            if(this.chartBar) {
                this.chartBar.setOption(opts)
            } else {
                this.initBar(opts)
            }
        })
    },
    initBar: function(options) {
        this.compBar.init((canvas, width, height, dpr) = > {
            const chart = echarts.init(canvas, null, {
              width: width,
              height: height,
              devicePixelRatio: dpr
            });
            
            // This is to inject some initialization items into chart. The data items are initialized to an empty array
            configBar(chart)
            chart.setOption(option)
        
            this.chartBar = chart
            return chart
        })
    }
});
Copy the code

Select ec-Canvas from selectComponent and initialize it manually by calling init. When data is updated, call chartinstance.setoption to update it.

Code organization

In addition to the data, the chart configuration items such as the axes, lengend, label, etc., are fixed and can be managed in a config file, such as configBar in the code above:

// chart-config.js
export function configBar(chart) {
    const opts = {
        //...各种配置项
        dataset: {
            dimensions: [],
            source: []
        },
        series: [
            {
                type: 'bar'
            }
        ]
    }
    chart.setOption(option)
}
Copy the code

If the diagram needs to be reused, it can be further encapsulated as a small program custom component:

<view class="report-group-bar">
  <ec-canvas id="{{chartDomId}}" canvas-id="{{canvasId}}" ec="{{ec}}" type="2d"></ec-canvas>
</view>
Copy the code
import * as echarts from '.. /.. /ec-canvas/echarts'

Component({
  properties: {
    chartId: {
      type: String.value: 'chart-group-bar'
    },
    canvasId: {
      type: String.value: 'canvas-group-bar'
    },
    chartData: {
      type: Array.value: []}},data: {
    ec: {
      lazyLoad: true}},lifetimes: {
    attached() {
      this.chartComp = this.selectComponent(this.properties.chartId)
    }
  },

  methods: {
    initChart(options) {
      this.chartComp && this.chartComp.init((canvas, width, height, dpr) = > {
        const chart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr
        })
        configChart(chart)
        chart.setOption(options)
        this.chart = chart
        return chart
      })
    }
  },

  observers: {
    'chartData': function (value) {
      const opts = {
        // ...
      }
      if (this.chart) {
        this.chart.setOption(opts)
      } else {
        this.initChart(opts)
      }
    }
  }
})
Copy the code

other

Small program basic library 2.9.0 supports a new Canvas 2D interface), using the new Canvas 2D can improve the rendering performance and solve the rendering problem of different layers, it is strongly recommended to enable:

<view class="report-group-bar">
  <ec-canvas id="{{chartDomId}}" canvas-id="{{canvasId}}" ec="{{ec}}" type="2d"></ec-canvas>
</view>
Copy the code