1、首先下载echarts插件https://github.com/ecomfe/echarts-for-weixin

2、把ec-canvas文件放入项目,我是放在pages外面的

3、在一个页面使用图表

wxml中:

<view class='card'>
    <ec-canvas id="mychart" canvas-id="mychart-bar" ec="{{ ec }}"></ec-canvas>
</view>

注意,ec-canvas外面的view必须设置高度,之前没有设置,图表不出现,找了好久的原因。

js:

首先引入js: 

import * as echarts from '../../ec-canvas/echarts';

声明一个全局变量

var barChart = null;

在data里:

ec: {
   onInit: function (canvas, width, height) {
        barChart = echarts.init(canvas, null, {
          width: width,
          height: height
        });
        canvas.setChart(barChart);
        return barChart;
      }
},

获取数据方法:

getData() {
    wx.showLoading({
      title: '加载中...',
    });
    let that = this;
    wx.request({
      url: 'https://list',
      method: 'get',
      data: {
        year: that.data.year
      },
      dataType: 'jsonp',
      success: function (res) {
        wx.hideLoading();
        console.log(res);
        var data = JSON.parse(res.data);
        var datas = [];
          datas = [data[0].value1, data[0].value2, data[0].value3,
          data[0].value4, data[0].value5, data[0].value6, data[0].value7,
          data[0].value8, data[0].value9, data[0].value10, data[0].value11,
          data[0].value12,];
          
        var monthstr = ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"];
        console.log(datas);
        barChart.setOption({
          title: {
            text: "标题标题标题",
            left: 'center'
          },
          xAxis: {
            type: 'category',
            data: monthstr,
            axisLabel: {
              interval: 0
            }
          },
          yAxis: {
            type: 'value'
          },
          series: [{
            data: datas,
            type: 'bar',
            itemStyle: {
              normal: {
                label: {
                  show: true,
                  position: 'top',
                  textStyle: {
                    color: 'black'
                  },
                  formatter: '{c}'
                }
              }
            }
          }],
        });
        
      },
      fail: function (res) {
        console.log("执行失败:" + res);
      }
    })

  },

onLoad()调用方法:

onload: function(){
    this.getData();
}

 

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐