统计添加echart


下载文件 或者 github 下载

资源地址

资源下的 ec-canvas 移动到仓库下。可以自己在 echart 官网打包压缩下(体积小小很多)。

代码配置

1.页面元素

<view class="chart" wx:if="{{chartShow}}">
  <ec-canvas id="mychart-dom-bar" canvas-id="mychart-bar" ec="{{ ec }}"></ec-canvas>
</view>

2.css样式

.chart {
  width: 100%;
  height: 500rpx;
}

3.JS

//page外引入
import * as echarts from '../../components/ec-canvas/echarts';

//初始化图表
function setOption(chart, option) {
  chart.setOption(option)
  return chart;
}

Page({
  data: {
    chartShow: true, //图表是否显示
    ec: {
      lazyLoad: true, //延时加载 方便接口返回数据
    }
  },

  //初始化图表
  initChart: function () {
    this.ecComponent = this.selectComponent('#mychart-dom-bar');
    this.ecComponent.init((canvas, width, height, dpr) => {
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
      });
      var option = {
        legend: {
          orient: 'vertical',
          x: 'left',
          // data: ['饮食', '出行', '住宿']
        },
        title: {
          text: '饼图',
          show: false,
          left: 'center',
          top: 'center'
        },
        series: [{
          type: 'pie',
          label: {
            show: true,
            formatter: '{b} ¥{d}'
          },
          data: [{
              value: 335,
              name: '饮食'
            },
            {
              value: 234,
              name: '出行'
            },
            {
              value: 1548,
              name: '住宿'
            }
          ],
          radius: ['40%', '70%']
        }]
      };

      // chart.setOption(option)
      setOption(chart, option);

      // 将图表实例绑定到 this 上,可以在其他成员函数(如 dispose)中访问
      this.chart = chart;
      return chart;
    });

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.initChart();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // this.ecComponent = this.selectComponent('#mychart-dom-bar');
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})

4.展示效果

作者:admin  创建时间:2021-12-12 15:36
最后编辑:admin  更新时间:2023-04-10 15:46