ECharts官方维护的一个开源项目,提供了一个微信小程序组件(Component),我们可以通过这个组件在微信小程序中使用 ECharts 绘制图表,非常方便好用。
下载链接:https://gitcode.net/mirrors/ecomfe/echarts-for-weixin/-/tree/master
1.引入
将ec-canvas 放入项目,随意放,但一般放到components
2.在页面中注册组件(.json)
"usingComponents": {
"ec-canvas": "/ec-canvas/ec-canvas" // 找到你的地址即可
}
3.在页面中使用组件(.wxml)
<view class="chart-content">
<ec-canvas id="mychart-dom-bar" canvas-id="mychart-bar" ec="{{ chartBar }}"></ec-
canvas>
</view>
.chart-content {
width: 100%;
height: 300rpx;
}
4.在页面中引入相应js、及初始化 (.js)
import * as echarts from '../../../ec-canvas/echarts'; // 引入echarts.js
let chart = null;
//初始化图表
function initCharts(canvas, width, height,dpr) {
chart = echarts.init(canvas, null, {
width: width,
height: height,
devicePixelRatio: dpr // 像素
});
canvas.setChart(chart);
return chart;
}
Page({
data: {
chartBar: {
onInit: initCharts
},
},
onReady() { // 页面渲染完成后,获取图表数据
this.getChartData()
},
getChartData(){
const option = {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [
{
data: [150, 230, 224, 218, 135, 147, 260],
type: 'line'
}
]
}
setTimeout(()=> { // 模拟接口返回数据
// 获取 chart 实例的方式
console.log(chart)
chart.setOption(option); // 设置图表数据
}, 500);
}
});