Page设置
Page({
data: {
ec: {
lazyLoad: true,
},
},
init_echarts: function(){}
});
function getOptionOne(){}
wxml
<view style="height: 250rpx;">
<ec-canvas id="lineCanvas1" style="width:100%;" canvas-id="lineCanvas1" ec="{{ ec }}"></ec-canvas>
</view>
详细代码及使用方式
1.在Page中编写初始化公共方法,传入渲染数据和选择器和配置文件
init_echarts: function (chartData, id, optionFunc) {
this.selectComponent(id).init((canvas, width, height, dpr) => {
let variable = echarts.init(canvas, null, {
width: width,
height: height,
devicePixelRatio: dpr,
});
variable.setOption(optionFunc(chartData));
return variable
});
},
2.配置文件
function getOptionOne(chartData) {
return {
grid: {
x: "0%",
y: "0%",
height: "98%",
width: "100%",
containLabel: false,
},
xAxis: [
{
type: "category",
boundaryGap: false,
show: false,
},
],
yAxis: [
{
show: false,
scale: true,
axisLine: {
show: false,
},
axisTick: {
show: false,
},
splitLine: {
show: false,
},
},
],
series: [
{
data: chartData.actualIntake,
type: "line",
smooth: true,
showSymbol: false,
itemStyle: {
color: "",
},
lineStyle: {
width: 4,
color: "#4E70FF",
shadowOffsetX: 0,
shadowOffsetY: 0,
shadowBlur: 2,
shadowColor: "rgba(145, 132, 132, 0.2)",
},
areaStyle: {
color: {
type: "linear",
x: 0,
y: 0,
x2: 0,
y2: 1,
colorStops: [
{
offset: 0,
color: "rgba(56,92,223,0.48)",
},
{
offset: 1,
color: "rgba(30,209,193,0)",
},
],
global: false,
},
},
},
{
data: chartData.recommendedIntake,
type: "line",
smooth: true,
showSymbol: false,
itemStyle: {
color: "",
},
lineStyle: {
width: 4,
color: "#4efbc0",
shadowOffsetX: 0,
shadowOffsetY: 0,
shadowBlur: 2,
shadowColor: "#4efbc0",
},
areaStyle: {
color: {
type: "linear",
x: 0,
y: 0,
x2: 0,
y2: 1,
colorStops: [
{
offset: 0,
color: "rgba(233, 255, 252,1)",
},
{
offset: 1,
color: "rgba(233, 255, 252,0)",
},
],
global: false,
},
},
},
],
};
}
3.调用示例
this.init_echarts(
{
recommendedIntake: result01.jsonArray.map(
(item) => item.recommendedIntake
),
actualIntake: result01.jsonArray.map((item) => item.actualIntake),
},
"#lineCanvas1",
getOptionOne
);
4.补充,解决dom显示隐藏时,echarts不能正确渲染的问题
- 使用resize()api
let echartsInstance;
init_echartsRadarMap: function (chartData) {
if (echartsInstance) {
echartsInstance.resize();
} else {
this.radarMap = this.selectComponent("#radarMap");
this.radarMap.init((canvas, width, height, dpr) => {
echartsInstance = echarts.init(canvas, null, {
width: width,
height: height,
devicePixelRatio: dpr,
});
echartsInstance.setOption(this.getRadarMapOption(chartData));
return echartsInstance;
});
}
},
`resize()` 方法是 Echarts 提供的一个 API,用于重新调整图表的大小。当图表所在的 DOM 元素的尺寸发生变化时,或者当图表需要在不同的设备上显示时,您可以调用 `resize()` 方法来重新调整图表的大小,以适应新的尺寸。
具体来说,当您在隐藏 Echarts DOM 节点之后再显示 Echarts 时,如果不调用 `resize()` 方法,Echarts 可能无法正确地重新渲染,导致图表无法显示。因此,您可以在显示 Echarts 之前调用 `resize()` 方法,以确保图表能够正确地重新渲染并显示在页面上。