如何優雅的在小程式中使用EChart元件
阿新 • • 發佈:2019-02-02
EChart提供了微信小程式版本,掃描二維碼預覽demo
下載
下載下來,其中ec-canvas資料夾就是元件原始碼
使用
將ec-canvas元件放入小程式中,例如,components檔案中,
在app.json中的pages下,增加‘pages/pie/pie’,小程式則會自動生成一下幾個檔案:pie資料夾、pie.index、pie.json、pie.wxml、pie.wxss
pie.json中配置:路徑要正確
{
"usingComponents": {
"ec-canvas": "../../components/ec-canvas/ec-canvas"
}
}
pie.html
<view class="container">
<ec-canvas ec="{{ ec }}"></ec-canvas>
</view>
pie.exss
.container { 需要給container設定寬高
padding: 15rpx;
margin: 15rpx 0rpx;
width: 100%;
height: 50%;
box-sizing: border-box;
}
pie.js
官方demo使用方法
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 = {
backgroundColor: "#ffffff",
color: ["#37A2DA", "#32C5E9" , "#67E0E3", "#91F2DE", "#FFDB5C", "#FF9F7F"],
series: [{
label: {
normal: {
fontSize: 14
}
},
type: 'pie',
center: ['50%', '50%'],
radius: [0, '60%'],
data: [
{
value: 55,
name: '北京'
}, {
value: 20,
name: '武漢'
}, {
value: 10,
name: '杭州'
}, {
value: 20,
name: '廣州'
}, {
value: 38,
name: '上海'
}]
};
chart.setOption(option);
return chart;
}
Page({
data: {
ec: {
onInit: initChart
}
},
});
改版後
import * as echarts from '../../../components/ec-canvas/echarts';
function generatePieOptions (title) {
const option = {
title: {
text: title,
x: 'center'
},
series: [
{
label: {
normal: {
fontSize: 10,
position: 'inner'
}
},
type: 'pie',
center: ['50%', '50%'],
radius: [0, '30%'],
data: []
}]
}
return option;
}
const pieOption = generatePieOptions('使用權重');
function initChart (_pieOption) {
return function (canvas, width, height) {
const chart = echarts.init(canvas, null, {
width: width,
height: height
});
canvas.setChart(chart);
chart.setOption(_pieOption);
return chart;
}
}
Page({
data: {
ec: {
onInit: initChart(pieOption)
}
},
initOptions: function () {
pieOption.series[0].data = [
{ value: 55, name: '北京' },
{ value: 20, name: '武漢' },
{ value: 10, name: '杭州' },
{ value: 20, name: '廣州' },
{ value: 38, name: '上海' }
];
},
onLoad: function (options) {
this.initOptions();
}
})
個人經驗之談,如有更好的歡迎提出.