下载
首先,下载 GitHub 上的 ecomfe/echarts-for-weixin 项目。
引入组件
拷贝 ec-canvas 目录,参考下面几个文件的写法。
json 配置如下:
"usingComponents": {
"ec-canvas": "/ec-canvas/ec-canvas"
}
wxml 中:
<view class="ec-container">
<ec-canvas canvas-id="echart-pie" ec="{{ec}}"></ec-canvas>
</view>
js 中:
// home.js
import * as echarts from '../../ec-canvas/echarts';
Page({
data: {
// 1. 只传函数引用,不要加 ()
ec: {
onInit: initChart
}
},
onLoad() {
// 可以在这里发起网络请求,动态改 option
},
onReady() {
// 页面首次渲染完成
},
onShow() { },
onHide() { },
onUnload() { },
onPullDownRefresh() { },
onReachBottom() { },
// 右上角分享
onShareAppMessage() {
return {
title: '城市销量占比',
path: '/pages/home/home'
};
}
});
/* ======================================================
* 初始化函数,由 ec-canvas 组件在渲染后自动调用
* ====================================================== */
function initChart(canvas, width, height, dpr) {
const chart = echarts.init(canvas, null, {
width,
height,
devicePixelRatio: dpr
});
canvas.setChart(chart); // 兼容 v2 组件库
const option = {
backgroundColor: '#ffffff',
series: [{
type: 'pie',
center: ['50%', '50%'],
radius: ['20%', '40%'],
label: {
fontSize: 14
},
data: [
{ value: 55, name: '北京' },
{ value: 20, name: '武汉' },
{ value: 10, name: '杭州' },
{ value: 20, name: '广州' },
{ value: 38, name: '上海' }
]
}]
};
chart.setOption(option);
return chart; // 必须返回 chart 实例
}
scss中:
.ec-container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
width: 100vw;
height: 100vh;
}
ec-canvas {
width: 100%;
height: 100%;
}