WeChat applet chart development (eCharts)

1. Description

This article mainly records the use of charts in the development process of WeChat applets. Here we mainly explain the use of eCharts, and finally we will talk about the use of wecharts. As for the difference between the two, echarts is more powerful, but its volume is larger. It has imported more than 500K, even if it imports custom components, it is still very large; while wxcharts is not so powerful, but its volume is relatively small, especially the lightweight version. Only a little over 30K, which is very suitable for small programs with relatively high size requirements.

1. Use of echarts

(1) Download

The echarts downloaded here is the version adapted by others on the applet. download link

(2) Import echarts into the applet

Unzip the downloaded echarts-for-weixin-master compressed package, and then copy all the files in the ec-canvas folder directly to the applet. I copied it to the utils directory here.

Applet directory

(3) Perform related configuration and development

First of all, to reference related modules in the page, here is a new page named echarts, the relevant code of echarts.json:

{
    
    
  "navigationBarTitleText": "饼状图实现",
  "usingComponents": {
    
    
    "ec-canvas": "../../utils/ec-canvas/ec-canvas"
  }
}

The following is the code of echarts.wxml

<view class="econtainer">
  <ec-canvas id="mychart-dom-line" canvas-id="mychart-line" ec="{
     
     { ec }}"></ec-canvas>
</view>

Be sure to pay attention to the style of the control, because if the length and width are not set properly, the chart may not be displayed. Moreover, you must pay attention to the difference between rpx and px, especially when using wxcharts, otherwise the format will be messy on different mobile phones. The following is the code of echarts.wxss:

/* pages/echarts/echarts.wxss */
ec-canvas {
    
    
  width: 100%;
  height: 300px;
}

.econtainer {
    
    
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx 0;
  box-sizing: border-box;
}

The following is the code of the echarts.js file:

// pages/echarts/echarts.js
import * as echarts from '../../utils/ec-canvas/echarts'
const app = getApp();

function initPie(canvas, width, height) {
    
    
  const chart = echarts.init(canvas, null, {
    
    
    width: width,
    height: height
  });
  canvas.setChart(chart);

  var option = {
    
    
    title: {
    
    
      text: '饼状图',
      subtext: '纯属虚构',
      left: 'center'
    },
    tooltip: {
    
    
      trigger: 'item',
      formatter: '{b} : {c} ({d}%)'
    },
    legend: {
    
    
      orient: 'vertical',
      left: 'left',
      data: ['直接访问', '邮件营销', '联盟广告', '视频广告', '搜索引擎']
    },
    series: [
      {
    
    
        name: '项目:',
        type: 'pie',
        radius: '55%',
        center: ['50%', '60%'],
        label: {
    
    
          show: true,
          formatter: '{b}({d}%)'
        }, 
        data: [
          {
    
     value: 335, name: '直接访问' },
          {
    
     value: 310, name: '邮件营销' },
          {
    
     value: 234, name: '联盟广告' },
          {
    
     value: 135, name: '视频广告' },
          {
    
     value: 1548, name: '搜索引擎' }
        ],
        emphasis: {
    
    
          itemStyle: {
    
    
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  };

  chart.setOption(option);
  return chart;
}

Page({
    
    
  data: {
    
    
    ec: {
    
    
      onInit: initPie
    }
  },

  onReady() {
    
    
  }
});

The following is a running screenshot, debugging and running on the computer, some display is incomplete:
screenshot of pie chart

(4) Precautions

If you follow the above steps, you can directly copy the above code and it should work.

At this time, we will have a question, what if we change to other charts? We sorted out the echarts.js file and found that, in fact, we can change the option in the initPie method to other charts except that the entire framework remains unchanged. But there is one place, pay attention, that is, do not remove the var definition in front of the option, otherwise it will not work Display the graph. The following is the framework of echarts.js:

import * as echarts from '../../utils/ec-canvas/echarts'
const app = getApp();

function initPie(canvas, width, height) {
    
    
  const chart = echarts.init(canvas, null, {
    
    
    width: width,
    height: height
  });
  canvas.setChart(chart);

  var option = {
    
    
  };

  chart.setOption(option);
  return chart;
}

Page({
    
    
  data: {
    
    
    ec: {
    
    
      onInit: initPie
    }
  },

  onReady() {
    
    
  }
});

Why echarts is powerful, not only because it is more beautiful, but also, we can directly copy the example code on the echartsjs official website (note that it must be the chart of the option code, and others should be adapted by ourselves) to the initPie method of echarts.js In the option, some relatively simple charts can be directly copied and used, and then the data can be changed to the data you want.

Another question is, how to load two or more charts on the same page?

Just add a tag to the echarts.wxml file:

<!--index.wxml-->
<view class="econtainer">
  <ec-canvas id="mychart-dom-line" canvas-id="mychart-line" ec="{
     
     { ec }}"></ec-canvas>
</view>

<view class="econtainer">
  <ec-canvas id="mychart-dom-line" canvas-id="mychart-line" ec="{
     
     { cl }}"></ec-canvas>
</view>

Then add another method in echarts.js, and then initialize it in the data of the page. The following is the complete code of echarts.js with two charts:

// pages/echarts/echarts.js
import * as echarts from '../../utils/ec-canvas/echarts'
const app = getApp();

function initPie(canvas, width, height) {
    
    
  const chart = echarts.init(canvas, null, {
    
    
    width: width,
    height: height
  });
  canvas.setChart(chart);

  var option = {
    
    
    title: {
    
    
      text: '饼状图',
      subtext: '纯属虚构',
      left: 'center'
    },
    tooltip: {
    
    
      trigger: 'item',
      formatter: '{b} : {c} ({d}%)'
    },
    legend: {
    
    
      orient: 'vertical',
      left: 'left',
      data: ['直接访问', '邮件营销', '联盟广告', '视频广告', '搜索引擎']
    },
    series: [
      {
    
    
        name: '项目:',
        type: 'pie',
        radius: '55%',
        center: ['50%', '60%'],
        label: {
    
    
          show: true,
          formatter: '{b}({d}%)'
        }, 
        data: [
          {
    
     value: 335, name: '直接访问' },
          {
    
     value: 310, name: '邮件营销' },
          {
    
     value: 234, name: '联盟广告' },
          {
    
     value: 135, name: '视频广告' },
          {
    
     value: 1548, name: '搜索引擎' }
        ],
        emphasis: {
    
    
          itemStyle: {
    
    
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  };

  chart.setOption(option);
  return chart;
}

function initClomn(canvas, width, height) {
    
    
  const chart = echarts.init(canvas, null, {
    
    
    width: width,
    height: height
  });
  canvas.setChart(chart);

  var option = {
    
    
    title: {
    
    
      text: '柱形图'
    },
    color: ["#ff9966"],
    tooltip: {
    
    
      show: true,
      trigger: 'axis'
    },
    legend: {
    
    
      data: ['销量']
    },
    xAxis: {
    
    
      data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
    },
    yAxis: {
    
    },
    series: [{
    
    
      name: '销量',
      type: 'bar',
      data: [5, 20, 36, 10, 10, 20]
    }]
  };

  chart.setOption(option);
  return chart;
}

Page({
    
    
  data: {
    
    
    ec: {
    
    
      onInit: initPie
    },
    cl: {
    
    
      onInit: initClomn
    }
  },

  onReady() {
    
    
  }
});

screenshot:

screenshot

2. wxcharts

First download wxcharts , and then copy the wxcharts.js file to the utils folder.
Because the wxcharts code is easier to understand, it is to define a label, and then draw the chart according to the data in the js file, so the code is directly uploaded.
wxcharts.wxml file code:

<view class="mycontainer">
  <canvas canvas-id="feiyu1" class="canvas"></canvas>
</view>
<view class="mycontainer">
  <canvas canvas-id="feiyu2" class="canvas"></canvas>
</view>
<view class="mycontainer">
  <canvas canvas-id="feiyu3" class="canvas"></canvas>
</view>

wxcharts.wxss file code:

.canvas {
    
    
  width: 750rpx;
  height: 500rpx;
}
.mycontainer {
    
    
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx 0;
  box-sizing: border-box;
} 

Finally, the code of the wxcharts.js file, there are three charts:

//wxcharts.js
const util = require('../../utils/util.js');
var wxCharts = require('../../utils/wxcharts-min.js');

Page({
    
    
  data: {
    
    
  },
  onReady: function (e) {
    
    
    var windowWidth = 320;
    var windowHeight = 150;
    try {
    
    
      var res = wx.getSystemInfoSync();
      windowWidth = res.windowWidth;
      windowHeight = res.windowHeight;
    } catch (e) {
    
    
      console.error('getSystemInfoSync failed!');
    }

    new wxCharts({
    
    
      animation: true, //是否有动画
      canvasId: 'feiyu1',
      type: 'pie',
      series: [{
    
    
        name: '成交量1',
        data: 15,
      }, {
    
    
        name: '成交量2',
        data: 35,
      }, {
    
    
        name: '成交量3',
        data: 78,
      }],
      width: windowWidth,
      height: 200,
      dataLabel: true,
    });

    new wxCharts({
    
    
      animation:true,
      canvasId: 'feiyu2',
      type: 'line',
      categories: ['2015', '2016', '2017', '2018', '2019', '2020'],
      series: [{
    
    
        name: '成交量1',
        data: [0.15, 0.2, 0.45, 0.37, 0.4, 0.8],
        format: function (val) {
    
    
          return val.toFixed(2) + '万';
        }
      }, {
    
    
        name: '成交量2',
        data: [0.30, 0.37, 0.65, 0.78, 0.69, 0.94],
        format: function (val) {
    
    
          return val.toFixed(2) + '万';
        }
      }],
      yAxis: {
    
    
        title: '成交金额 (万元)',
        format: function (val) {
    
    
          return val.toFixed(2);
        },
        min: 0
      },
      width: windowWidth,
      height: 200
    });

    new wxCharts({
    
    
      canvasId: 'feiyu3',
      type: 'column',
      animation: true,
      categories: ['2013', '2014', '2015', '2016', '2017'],
      series: [{
    
    
        name: '订单量',
        color: '#188df0',
        data: [23, 28, 35, 54, 95],
        format: function (val, name) {
    
    
          return val.toFixed(2) + '万';
        }
      }],
      yAxis: {
    
    
        format: function (val) {
    
    
          return val + '万';
        },
        min: 0
      },
      xAxis: {
    
    
        disableGrid: false,
        type: 'calibration'
      },
      extra: {
    
    
        column: {
    
    
          width: 15,
        },
        legendTextColor: '#000000'
      },
      width: windowWidth,
      height: 200,
    });
  
  }
});

Effect screenshot:

Guess you like

Origin blog.csdn.net/qq_36224961/article/details/103974611