一、引入组件
直接拷贝 ec-canvas 目录到新建的项目下,GitHub上最新版本组件的下载地址。
其中提到的ec-canvas组件目录就在下载的echarts-for-weixin-master项目目录中
二、创建图表
1、首先在需要引入ECharts的小程序目录中的index.json文件中添加对组件ec-canvas的引入路径:
index.json 配置如下:
{
"usingComponents": {
"ec-canvas": "../../ec-canvas/ec-canvas"
}
}
注意:路径的相对位置要写对,要根据自己的目录做出调整,这里只是示例
2、在index.js文件中的结构如下:
首先,在js文件引入echarts
import * as echarts from '../../ec-canvas/echarts';
然后,复制官方文档给出的代码结构,使得图表能够在页面加载后被初始化并设置。
function initChart(canvas, width, height) {
const chart = echarts.init(canvas, null, {
width: width,
height: height
});
canvas.setChart(chart);
var option = {
//这里添加对图表得设置
};
chart.setOption(option);
return chart;
}
//在data对象中声明一个存放echarts数据的对象
Page({
data: {
ec: {
onInit: initChart
}
}
});
其中在var option = {……}添加所需图表的基础代码后再根据要求进行设置;
关于代码直接在官网给出的实例中选择符合自己需求的图表即可。
3、在index.wxml中使用ec-canvas组件,将定义好的ECharts图表引入到页面中,例如:
<view class="container">
<ec-canvas id="mychart-dom-bar" canvas-id="mychart-bar" ec="{{ ec }}"></ec-canvas>
</view>
注意:其中ec是一个在index.js中定义的对象
4、将在GitHub中下载的echarts-for-weixin-master项目打开,然后将里面的app.wxss中的代码复制到自己项目的app.wxss中
.container {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-between;
box-sizing: border-box;
}
ec-canvas {
width: 100%;
height: 100%;
}
然后在自己的index.wxss中添加样式,最后运行一下,效果就出来啦。