作为一个专业的图表绘制工具,echarts相对来说在交互和功能上更领先一些,但是引入后的代码大小会暴增600-1M左右,对于小程序上传主包不超过2M的限制来说,就要考虑根据实际情况如何定制化进行JS文件的优化。
首先引入后的wxml
<ec-canvas id="" canvas-id="mychart-line" ec="{{ ec }}"></ec-canvas>
其次在ready中定义
this.ecChart = this.selectComponent('#id');
之后在js文件中定义图表的数据options,例如:
var option = {
tooltip: {
trigger: 'axis',
axisPointer: { // 坐标轴指示器,坐标轴触发有效
type: 'shadow' // 默认为直线,可选为:'line' | 'shadow'
},
confine: true
},
legend: {
data: ['热度', '正面', '负面']
},
grid: {
left: 20,
right: 20,
bottom: 15,
top: 40,
containLabel: true
},
xAxis: [{
type: 'value',
axisLine: {
lineStyle: {
color: '#999'
}
},
axisLabel: {
color: '#666'
}
}],
yAxis: [{
type: 'category',
axisTick: {
show: false
},
data: ['汽车之家', '今日头条', '百度贴吧', '一点资讯', '微信', '微博', '知乎'],
axisLine: {
lineStyle: {
color: '#999'
}
},
axisLabel: {
color: '#666'
}
}],
series: [{
name: '热度',
type: 'bar',
label: {
normal: {
show: true,
position: 'inside'
}
},
data: [300, 270, 340, 344, 300, 320, 310],
itemStyle: {
// emphasis: {
// color: '#37a2da'
// }
}
},
{
name: '正面',
type: 'bar',
stack: '总量',
label: {
normal: {
show: true
}
},
data: [120, 102, 141, 174, 190, 250, 220],
itemStyle: {
// emphasis: {
// color: '#32c5e9'
// }
}
},
{
name: '负面',
type: 'bar',
stack: '总量',
label: {
normal: {
show: true,
position: 'left'
}
},
data: [-20, -32, -21, -34, -90, -130, -110],
itemStyle: {
// emphasis: {
// color: '#67e0e3'
// }
}
}
]
};
当然,数据可以设置成动态数据,从小程序的集合collection中获取,注意位置要放正确。
function ecChart1(canvas, width, height, dpr) {
const chart = echarts.init(canvas, null, {
width: width,
height: height,
devicePixelRatio: dpr //加上这个参数可以让图表显示更清晰
});
canvas.setChart(chart);
//这里获取集合数据
但是在曲线绘制过程中,出现一个小问题就是渐变区域areastyle的显示问题,在各种参数都正确的情况下,在小程序刚加载完毕后不能显示渐变效果,需要手势点击触碰一下才可以,这个问题尚未能找到解决方法。
示例代码:
areaStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
offset: 0,
color: 'rgb(7,193,96,0.5)'
},
{
offset: 0.2,
color: 'rgb(7,193,96,0.2)'
},
{
offset: 1,
color: 'rgb(7,193,96,0.1)'
}
]),
},
lineStyle: {
width: 3,
color: 'rgb(7,193,96)',
},
如有遇到类似问题已经解决的朋友,欢迎评论指出。