微信小程序使用echarts

1.下载

https://github.com/ecomfe/echarts-for-weixin直接将一整个项目下载下来,将下载下来的项目里的ec-canvas文件复制粘贴到项目文件夹中

 2.引入

在要用到的页面json文件中引入

 3.使用

js文件

import * as echarts from '../../ec-canvas/echarts' // 这个是自己实际的目录
function initChart(canvas, width, height, dpr) { // 这部分是固定的不需要 是通用的
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height
  });
  canvas.setChart(chart);
  // 这是 唯一需要更改的,可根据实际情况api更改图标
  // 我这边测试的是一个 普通的折线图,案例网址:
  var option = {
    xAxis: {
        type: 'category',
        data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    },
    yAxis: {
        type: 'value'
    },
    series: [{
        data: [820, 932, 901, 934, 1290, 1330, 1320],
        type: 'line'
    }]
};

  chart.setOption(option);
  return chart;
}

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

 wxml文件

<view class="my-chart">
    <ec-canvas id="mychart-dom-graph" canvas-id="mychart-graph" ec="{
   
   { ec }}"></ec-canvas>
</view>

 wxss(这里一定要写,不然将是一片空白)

.my-chart {
    width: 650rpx;
    height: 600rpx;
}
ec-canvas {
    width: 100%;
    height: 100%;
}

4.配置项

4.1 tooltip

tooltip: {
   show:true, //是否显示悬浮框
   trigger: 'item'/'axis'/'none', //数据项图形触发/坐标轴触发/什么都不触发
   position: 'top', //显示在图形上方
}

4.1.1 tooltip.formatter

1.字符串模板

模板变量有 {a}{b}{c}{d}{e},分别表示系列名,数据名,数据值等。 在 trigger 为 'axis' 的时候,会有多个系列的数据,此时可以通过 {a0}{a1}{a2} 这种后面加索引的方式表示系列的索引。 不同图表类型下的 {a}{b}{c}{d} 含义不一样。 其中变量{a}{b}{c}{d}在不同图表类型下代表数据含义为:

  • 折线(区域)图、柱状(条形)图、K线图 : {a}(系列名称),{b}(类目值),{c}(数值), {d}(无)

  • 散点图(气泡)图 : {a}(系列名称),{b}(数据名称),{c}(数值数组), {d}(无)

  • 地图 : {a}(系列名称),{b}(区域名称),{c}(合并数值), {d}(无)

  • 饼图、仪表盘、漏斗图: {a}(系列名称),{b}(数据项名称),{c}(数值), {d}(百分比)

更多其它图表模板变量的含义可以见相应的图表的 label.formatter 配置项。

formatter: '{b0}: {c0}<br />{b1}: {c1}'

2.回调函数

formatter:function(params){
   return params.marker +" " +params.name+":"+ params.value + "%";
}

params参数

{
    componentType: 'series',
    // 系列类型
    seriesType: string,
    // 系列在传入的 option.series 中的 index
    seriesIndex: number,
    // 系列名称
    seriesName: string,
    // 数据名,类目名
    name: string,
    // 数据在传入的 data 数组中的 index
    dataIndex: number,
    // 传入的原始数据项
    data: Object,
    // 传入的数据值。在多数系列下它和 data 相同。在一些系列下是 data 中的分量(如 map、radar 中)
    value: number|Array|Object,
    // 坐标轴 encode 映射信息,
    // key 为坐标轴(如 'x' 'y' 'radius' 'angle' 等)
    // value 必然为数组,不会为 null/undefied,表示 dimension index 。
    // 其内容如:
    // {
    //     x: [2] // dimension index 为 2 的数据映射到 x 轴
    //     y: [0] // dimension index 为 0 的数据映射到 y 轴
    // }
    encode: Object,
    // 维度名列表
    dimensionNames: Array<String>,
    // 数据的维度 index,如 0 或 1 或 2 ...
    // 仅在雷达图中使用。
    dimensionIndex: number,
    // 数据图形的颜色
    color: string,


    // 饼图的百分比
    percent: number,


}

4.2 隐藏背景网格线

splitLine: {show: false},

5. 一个页面使用多个echarts图形

js

import * as echarts from '../ec-canvas/echarts';
import {data} from '../data.js'
let Chart = [];
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isShoweyes: true,
    turnoverEc: {
      lazyLoad: true,
    },
    customerEc: {
      lazyLoad: true,
    },
    priceEc: {
      lazyLoad: true,
    },
    echartsData: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.echartsComponnet1 = this.selectComponent('#mychart-dom-turnover');
    this.echartsComponnet2 = this.selectComponent('#mychart-dom-customer');
    this.echartsComponnet3 = this.selectComponent('#mychart-dom-price');
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 重置图表存储容器 不然会报错
    Chart = [];
    this.getData(); //获取数据
  },
  // 初始化数据
  getData: function () {
    // 金额格式化
    for (const key in data.orderPriceCountRespVo) {
      data.orderPriceCountRespVo[key] = this.filterMoney(data.orderPriceCountRespVo[key]);
    }
    for (const key in data.shopPersonInfoRespVo) {
      data.shopPersonInfoRespVo[key] = this.filterMoney(data.shopPersonInfoRespVo[key]);
    }
    this.setData({
      echartsData: data
    }, () => {
      for (let i = 1; i < 4; i++) {
        if (!Chart[i]) {
          this.initEcharts(i); //初始化图表
        } else {
          this.setOption(i); //更新数据
        }
      }
    })
  },
  //初始化图表
  initEcharts: function (i) {
    this['echartsComponnet' + i].init((canvas, width, height) => {
      // 初始化图表
      Chart[i - 1] = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      this.setOption(i);
      // 注意这里一定要返回 chart 实例,否则会影响事件处理等
      return Chart[i - 1];
    });
  },
  setOption: function (i) {
    Chart[i - 1].clear(); // 清除
    Chart[i - 1].setOption(this['getOption' + i]()); //获取新数据
  },
  handeltosee() {
    this.setData({
      isShoweyes: !this.data.isShoweyes
    });
  },
  // 格式化Tooltip
  formatterTooltip(param) {
    return "日期:" + param[0].name + "\n" + param[0].seriesName + ": " + param[0].data
  },
  // 更改Tooltip的位置,处理边界超出的情况
  setTooltipPositionfunction(point, params, dom, rect, size) {
    console.log(params, dom)
    //其中point为当前鼠标的位置,size中有两个属性:viewSize和contentSize,分别为外层div和tooltip提示框的大小
    // 更改提示框的显示位置
    let x = point[0];//
    let y = point[1];
    // size: 包括 dom 的尺寸和 echarts 容器的当前尺寸,例如:{contentSize: [width, height], viewSize: [width, height]}
    let boxWidth = size.contentSize[0];
    // let boxHeight = size.contentSize[1]; // size里面此处获取不到dom的高度,值为NAN,所以下面指定了一个固定值
    let boxHeight = 50;
    let posX = 0;//x坐标位置
    let posY = 0;//y坐标位置
    if (x < boxWidth) {//左边放不开
      posX = 5;
    } else {//左边放的下
      posX = x - boxWidth;
    }

    if (y < boxHeight) {//上边放不开
      posY = 5;
    } else {//上边放得下
      posY = y - boxHeight;
    }
    return [posX, posY];
  },
  getOption1() {
    let {
      echartsData
    } = this.data;
    return {
      color: ['#0179FF'],
      tooltip: {
        trigger: 'axis',
        axisPointer: { // 坐标轴指示器,坐标轴触发有效
          type: 'shadow', // 默认为直线,可选为:'line' | 'shadow'
          shadowStyle: {
            opacity: 0.8
          }
        },
        formatter: this.formatterTooltip,
        position: this.setTooltipPositionfunction
      },
      grid: {
        left: 20,
        right: 20,
        bottom: 15,
        top: 40,
        containLabel: true
      },
      xAxis: [{
        type: 'category',
        axisLine: {
          lineStyle: {
            color: '#999',
          }
        },
        axisLabel: {
          color: '#666',
        },
        data: echartsData.totalRecentRansactions.dates,
      }
      ],
      yAxis: [{
        type: 'value',
        axisTick: {
          show: false
        },
        axisLine: {
          show: false,
          lineStyle: {
            color: '#999',
          }
        },
        axisLabel: {
          color: '#666',
          fontSize: 13
        }
      }],
      series: [{
        name: '订单总额',
        type: 'line',
        label: {
          normal: {
            show: true,// 是否在折线点上显示数值
            position: 'inside'
          }
        },
        data: echartsData.totalRecentRansactions.allTotalMoney
      }]
    };
  },
  getOption2() {
    let {
      echartsData
    } = this.data;
    return {
      color: ['#6EB3FF'],
      tooltip: {
        trigger: 'axis',
        axisPointer: { // 坐标轴指示器,坐标轴触发有效
          type: 'shadow', // 默认为直线,可选为:'line' | 'shadow'
          shadowStyle: {
            opacity: 0.8
          }
        },
        position: ['60%', '20%'],
        formatter: this.formatterTooltip,
        position: this.setTooltipPositionfunction
      },
      xAxis: {
        data: echartsData.shopNewCustomerRespVo.dates
      },
      yAxis: {
        axisTick: {
          show: false
        },
        axisLine: {
          show: false,
          lineStyle: {
            color: '#999',
          }
        },
        axisLabel: {
          color: '#666',
          fontSize: 13
        }
      },
      series: [{
        name: '新增客户数',
        type: 'bar',
        data: echartsData.shopNewCustomerRespVo.allNewCustomer
      }]
    }
  },
  getOption3() {
    let {
      echartsData
    } = this.data;
    return {
      color: ['#0179FF'],
      tooltip: {
        trigger: 'axis',
        axisPointer: { // 坐标轴指示器,坐标轴触发有效
          type: 'shadow', // 默认为直线,可选为:'line' | 'shadow'
          shadowStyle: {
            opacity: 0.8
          }
        },
        position: ['60%', '20%'],
        formatter: this.formatterTooltip,
        position: this.setTooltipPositionfunction
      },
      grid: {
        left: 20,
        right: 20,
        bottom: 15,
        top: 40,
        containLabel: true
      },
      xAxis: [{
        type: 'category',
        axisLine: {
          lineStyle: {
            color: '#999'
          }
        },
        axisLabel: {
          color: '#666'
        },
        data: echartsData.customerOrderAverageRespVo.dates
      }],
      yAxis: [{
        type: 'value',
        axisTick: {
          show: false
        },
        axisLine: {
          show: false,
          lineStyle: {
            color: '#999'
          }
        },
        axisLabel: {
          color: '#666',
          fontSize: 13
        }
      }],
      series: [{
        name: '日均客单价',
        type: 'line',
        label: {
          normal: {
            show: true,
            position: 'inside'
          }
        },
        data: echartsData.customerOrderAverageRespVo.customerAverage
      },]
    };
  },
})

wxml

<!--图表1-->
<view class="echarts-container" hidden="{
   
   {!isShoweyes || !echartsData.totalRecentRansactions.allTotalMoney}}">
    <ec-canvas id="mychart-dom-turnover" canvas-id="mychart-turnover" ec="{
   
   { turnoverEc }}"></ec-canvas>
</view>
<!--图表2-->
<view class="echarts-container" hidden="{
   
   {!isShoweyes || !echartsData.shopNewCustomerRespVo.allNewCustomer}}">
    <ec-canvas id="mychart-dom-customer" canvas-id="mychart-customer" ec="{
   
   { customerEc }}"></ec-canvas>
</view>
<!--图表3-->
<view class="echarts-container" hidden="{
   
   {!isShoweyes || !echartsData.customerOrderAverageRespVo.customerAverage}}">
    <ec-canvas id="mychart-dom-price" canvas-id="mychart-price" ec="{
   
   { priceEc }}"></ec-canvas>
</view>

猜你喜欢

转载自blog.csdn.net/A_D_H_E_R_E/article/details/120113666
今日推荐