专家们走过路过看一下,求求了。
已经获得xAxisData、yAxisData的数据,怎么才能显示折线图!
求各位帮帮忙
onLoad(options) {
let yearMonth = options.yearMonth;
yearMonth = yearMonth.replace("年", "-").replace("月", "");
const systemInfo = wx.getWindowInfo();
this.setData({
canvasWidth: systemInfo.windowWidth,
canvasHeight: 300,
yearMonth: yearMonth,
});
request({
url: "...",
method: "get",
}).then((res) => {
const itemList = res.data.map((item) => {
const dataItems = [
...
];
const dateParts = item.testDate.split("-");
const day = dateParts[dateParts.length - 1];
return {
testDate: item.testDate.replace("-", "年").replace("-", "月") + "日",
date: day,
dataItems: dataItems,
pm25: parseFloat(item.pm25 || "0"),
};
});
const firstSevenItems = itemList.slice(0, 7);
const xAxisData = firstSevenItems.map((item) => item.date);
const yAxisData = firstSevenItems.map((item) => item.pm25);
this.setData(
{
itemList,
xAxisData,
yAxisData,
},
() => {
wx.hideLoading();
this.createChart();
}
);
});
},
createChart() {
const query = wx.createSelectorQuery();
query
.select("#lineCanvas")
.fields({ node: true, size: true })
.exec((res) => {
if (!res || !res[0] || !res[0].node) {
console.error("Canvas element not found");
return;
}
try {
const canvas = res[0].node;
const ctx = canvas.getContext("2d");
const dpr = wx.getWindowInfo().pixelRatio;
const canvasWidth = this.data.canvasWidth;
const canvasHeight = this.data.canvasHeight;
canvas.width = canvasWidth * dpr;
canvas.height = canvasHeight * dpr;
ctx.scale(dpr, dpr);
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (!this.data.xAxisData || !this.data.yAxisData) {
throw new Error("Chart data is missing");
}
// 直接创建新的图表实例
lineChart = new wxCharts({
canvas: canvas,
ctx: ctx,
type: "line",
categories: this.data.xAxisData,
series: [
{
name: "PM2.5浓度",
data: this.data.yAxisData,
format: function (val) {
return val.toFixed(2);
},
},
],
xAxis: {
disableGrid: false,
gridColor: "#cccccc",
fontColor: "#666666",
title: "日期",
},
yAxis: {
title: "PM2.5浓度(ug/m³)",
format: function (val) {
return val.toFixed(2);
},
min: 0,
gridColor: "#cccccc",
fontColor: "#666666",
},
width: this.data.canvasWidth,
height: this.data.canvasHeight,
dataLabel: true,
dataPointShape: true,
legend: false,
extra: {
lineStyle: "curve",
},
});
} catch (error) {
console.error("Chart creation error:", error);
wx.showToast({
title: "图表创建失败",
icon: "none",
duration: 2000,
});
}
});
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady() {
setTimeout(() => {
if (this.data.xAxisData && this.data.yAxisData) {
this.createChart();
}
}, 300);
},
/**
* 生命周期函数--监听页面显示
*/
onShow() {
const systemInfo = wx.getWindowInfo();
this.setData(
{
canvasWidth: systemInfo.windowWidth,
canvasHeight: 300,
},
() => {
if (this.data.xAxisData && this.data.yAxisData) {
this.createChart();
}
}
);
},