preface

Introducing Echart visualizations on the Web is a common operation, but how about using them in applets

Effect of the sample

  • Full sample effects – can be viewed here

Download using EC-Canvas

Download the echarts-for-Weixin code on Github and copy the EC-Canvas folder to the root directory, the same as the Pages directory, or place it in the Components custom component folder

When referring to EC-Canvas, the relative path is introduced correctly

Pages /piecharts

Configure the json

{
  "usingComponents": {
    "ec-canvas": ".. /.. /components/ec-canvas/ec-canvas"}}Copy the code

wxml

<view>
  <view class="pie-charts">
    <ec-canvas
      id="mychart-dom-bar"
      canvas-id="mychart-bar"
      ec="{{ ec }}"
    ></ec-canvas>
  </view>
</view>
Copy the code

wxss

.pie-charts {
  width: 100%;
  height: 500rpx; // Be sure to give ec-canvasOutermost one height, otherwisecanvasIt won't show upmargin: 20px 0 0 10px;
}
Copy the code

js

// pages/piecharts/piecharts.js
// To import echarts, be sure to import echarts.js in ec-canvas
import * as echarts from '.. /.. /components/ec-canvas/echarts';
// Chart options
let option = {
  title: {
    / / title
    text: 'Pie Chart Example'.x: 'center',},tooltip: {
    / / tip tip
    trigger: 'item'.formatter: '{a} \n{b} : {c} ({d}%)',},series: [{name: 'Access source'.type: 'pie'.radius: ['50%'.'70%'].avoidLabelOverlap: false.label: {
        show: false.position: 'center',},legend: {
        orient: 'vertical'.left: 'left'.data: ['front end'.'back-end'.'applet'.'Interview questions'.'read'],},emphasis: {
        label: {
          show: true.fontSize: '20'.fontWeight: 'bold',}},labelLine: {
        show: false,},data: [
        // Show the data, in general, just dynamically replace the data here, note that the small program newline with \n instead of br
        { value: 335.name: 'Front end \n 23%' },
        { value: 310.name: 'back-end' },
        { value: 234.name: 'applet' },
        { value: 135.name: 'Interview questions' },
        { value: 1548.name: 'read'},].itemStyle: {
        / / the shadow
        emphasis: {
          shadowBlur: 10.shadowOffsetX: 0.shadowColor: 'rgba (0, 0, 0, 0.5)',},},},],};let chart;
// The diagram is initialized
function initChart(canvas, width, height, dpr) {
  chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr, / / pixel
  });
  canvas.setChart(chart);
  chart.setOption(option);
  return chart;
}

Page({
  /** * initial data for the page */
  data: {
    ec: {
      onInit: initChart,
    },
  },

  /** * lifecycle function -- listens for page loading */
  onLoad: function(options) {}});Copy the code

Matters needing attention

  1. Introduce the EC-Canvas component in the configuration JSON file in the reference chart page of the applet. Make sure that the path is referenced correctly

  2. In the logic page, import echarts manually before using EC-charts, i.e. import * as echarts from ‘.. /.. /xxxx/ec-canvas/echarts’;

  3. In the WXSS of the page, you need to give a height to the outermost layer of ec-Canvas. The default height of EC-Canvas is 0

  4. For details about parameter Settings, see the echarts official documentation

How to modify the ec-Canvas default data

We know how to render the data to the page, but how to change the default initialization data by overwriting the original data structure with the new data

Update and restore chart data

// If you want to update the data below, it is usually returned in the background
// The data fields returned in the background may be different from the fields in the chart, but the structure must be the same
const pieObj = {
  updatelegends: ['eat'.'date'.'shopping'.'travel'.'treat'].updateExpendData: [{money: 1500.type: 'eat' },
    { money: 2000.type: 'date' },
    { money: 300.type: 'shopping' },
    { money: 400.type: 'travel' },
    { money: 600.type: 'treat'},].resetlegend: ['front end'.'back-end'.'applet'.'Interview questions'.'read'].resetExpendData: [{value: 335.name: 'front end' },
    { value: 310.name: 'back-end' },
    { value: 234.name: 'applet' },
    { value: 135.name: 'Interview questions' },
    { value: 1548.name: 'read'},]};module.exports = pieObj; // Export data
Copy the code

WXML updates data

<view class="change-box">
  <view class="update-btn btn" bindtap="onUpdate">Update the data</view>
  <view class="reset-btn btn" bindtap="onResetDate">Restore data</view>
</view>
Copy the code

Style code

/* pages/piecharts/piecharts.wxss */
.pie-charts {
  width: 100%;
  height: 500rpx; // The outer layer of the chart needs to be set to a height, otherwise echarts will not display it. The default height is0
  margin: 20px 0 0 10px;
}

.change-box {
  display: flex;
  justify-content: center;
}

.btn {
  width: 80px;
  height: 40px;
  text-align: center;
  line-height: 40px;
  border-radius: 5px;
  color: #fff;
}

.update-btn {
  background: #f56c6c;
  margin-right: 10px;
}

.reset-btn {
  background: #409eff;
}
Copy the code

** Logical code **

// pages/piecharts/piecharts.js
/ / introduce echarts
import * as echarts from '.. /.. /components/ec-canvas/echarts';

const pieData = require('./date'); // Import data

/ / options
let option = {
  // Initialize the data
  title: {
    text: 'Pie Chart Example'.x: 'center',},legend: {
    orient: 'vertical'.left: 'left'.data: ['front end'.'back-end'.'applet'.'Interview questions'.'read'],},tooltip: {
    trigger: 'item'.formatter: '{a} \n{b} : {c} ({d}%)',},series: [{name: 'Access source'.type: 'pie'.radius: ['50%'.'70%'].avoidLabelOverlap: false.label: {
        show: false.position: 'center',},legend: {
        orient: 'vertical'.left: 'left'.data: ['front end'.'back-end'.'applet'.'Interview questions'.'read'],},emphasis: {
        label: {
          show: true.fontSize: '20'.fontWeight: 'bold',}},labelLine: {
        show: false,},data: [{value: 335.name: 'Front end \n 23%' },
        { value: 310.name: 'back-end' },
        { value: 234.name: 'applet' },
        { value: 135.name: 'Interview questions' },
        { value: 1548.name: 'read'},].itemStyle: {
        emphasis: {
          shadowBlur: 10.shadowOffsetX: 0.shadowColor: 'rgba (0, 0, 0, 0.5)',},},},],};let chart;

function initChart(canvas, width, height, dpr) {
  chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr, / / pixel
  });
  canvas.setChart(chart);
  chart.setOption(option);
  return chart;
}

Page({
  /** * initial data for the page */
  data: {
    ec: {
      onInit: initChart,
    },
  },

  /** * lifecycle function -- listens for page loading */
  onLoad: function(options) {},

  // Update data
  onUpdate() {
    console.log(pieData);
    const expendData = pieData.updateExpendData;
    const legend = pieData.updatelegends;
    const newExpends = expendData.map((item) = > {
      return {
        name: item.type, // Because the data structure field is not the same, so the assignment, modify
        value: item.money, // If the data field returned by the back end is the same as the chart interface field, it can be ignored
      };
    });
    option.legend.data = legend;
    option.series[0].data = newExpends;

    if (chart) {
      chart.setOption(option); // You need to reset Option to take effect}},// Restore data
  onResetDate() {
    const expendData = pieData.resetExpendData;
    const legend = pieData.resetlegend;
    option.legend.data = legend; // Because the interface field is the same as the background return field, it can be directly assigned
    option.series[0].data = expendData;

    if (chart) {
      chart.setOption(option); // You need to reset Option to take effect}}});Copy the code

Pay attention to

The only caveat is that you do not change the internal data structure of the chart rendering when the data structure fields in the interface returned behind the scenes do not match the chart

For example, the name and value fields in legend and Data under Series above need to be reprocessed in the foreground if the subsegments returned by the back end are different

In the above update data, when the background return field money and type, when the update data, need to re-assign the value

Finally, setOption is required to reset the data, otherwise the chart data will not be updated, which is a little different from using VUE – Echarts versus Echarts alone

Effect of instance

conclusion

Using ec-Canvas is a component that can be used to create a graph echarts. When using ec-Canvas, note:

Import the path to the EC-Canvas component, and also import the component’s echart.js file in the page you use

For the basic configuration of a chart, refer to the official echarts document. When updating the data of a chart, note the following: Keep the structure consistent and do not modify the fields in the internal data structure of the chart

When the data field returned by the backend is inconsistent with the chart field, you can reassign the data after you get the data from the data interface. Finally, don’t forget to reset the setOption data

There are a lot of charts related content, if you are related to the chart problem, welcome to study together, leave a message, discuss..

The related documents

  • Apache ECharts- wechat applets version
  • Echarts official documentation
  • Introduce Echart chart to draw round pie chart