1. 首先下载echarts微信版
地址: https://github.com/ecomfe/echarts-for-weixin/tree/master/ec-canvas
下载后文件夹,放到项目根目录结构如图:
2、在使用的.xml中写入:
<view class="onOffChart"> <ec-canvas ec="{{onOffChartPie}}" id="onOffChartPie"> </ec-canvas> </view>
3. 在对应的json文件中添加:
"usingComponents": { "ec-canvas": "../../../ec-canvas/ec-canvas" }
4. 在js文件中使用:
import * as echarts from '../ec-canvas/echarts'; Page({ data: { //饼图 onOffChartPie: { // 将 lazyLoad 设为 true 后,需要手动初始化图表 lazyLoad: true } }, // 初始化饼图 initPieChart(loop_numbers, series_data) { // 获取组件 let ecComponent = this.selectComponent('#onOffChartPie'); ecComponent.init((canvas, width, height, dpr) => { // 获取组件的 canvas、width、height 后的回调函数 // 在这里初始化图表 const chart = echarts.init(canvas, null, { width: width, height: height, devicePixelRatio: dpr // new }); //调用设定EChart报表状态的函数,并且把从后端拿到的数据传过去 this.setPieOption(chart, loop_numbers, series_data); // 注意这里一定要返回 chart 实例,否则会影响事件处理等 return chart; }); }, //设定饼图状态 setPieOption(chart, loop_numbers, series_data) { var option = { backgroundColor: "#ffffff", color: ['#3585FF', '#F52F3E'], series: [{ label: { normal: { show: true, position: 'center', formatter: '{total|' + loop_numbers + '}' + '\n\r' + '{name|' + '回路总数' + '}', rich: { total: { fontSize: 20, color: '#1A1A28', fontWeight: 'bold', lineHeight: 35 }, name: { fontSize: 14, color: '', lineHeight: 10, }, } }, emphasis: { //中间文字显示 show: true, } }, type: 'pie', center: ['50%', '50%'], radius: ['96%', '75%'], data: series_data }], }; chart.setOption(option); }, // 获取回路详情 getDeviceLoopDetails() { ProjectSituation.getInstance().deviceLoopDetails() .request( success => { let loopType = success.Data.loop_type, loopOnOffList = [], loopOnNum = 0, loopOffNum = 0; loopType.forEach(item => { if (item.name == '开') { loopOnNum = item.value } else if (item.name == '关') { loopOnNum += item.value } else if (item.name == '离线') { loopOffNum = item.value } }) loopOnOffList = [{ value: loopOnNum, name: '在线' }, { value: loopOffNum, name: '离线' }, ] this.setData({ // loop_numbers: success.Data.loop_numbers || '--', loopOnNum: loopOnNum, loopOffNum: loopOffNum, }) this.initPieChart(success.Data.loop_numbers, loopOnOffList) }, fail => { console.log(fail) } ) }, onLoad: function (options) { // 接口请求 this.getDeviceLoopDetails() }, })