如何在Chart.js中使用多个折线图?数据更新同步问题求助
问题原因
因为数组是引用类型,你初始化三个图表时共用了同一个initialData和initialLabels数组,导致三个图表的data指向同一块内存地址。不管修改哪个图表的data或labels,都会同步影响其他两个图表。
解决方法
1. 为每个图表创建独立的数组副本
初始化时不要直接复用同一个数组,用slice()方法创建数组的浅拷贝,保证每个图表的data和labels都是独立引用:
// 基础初始数据模板 const baseInitialData = new Array(10).fill(0); const baseInitialLabels = ['0', '-1', '-2', '-3', '-4', '-5', '-6', '-7', '-8', '-9']; // 电流图表初始化 currentAmpChart = new Chart(document.getElementById('amperageChart').getContext('2d'), { type: 'line', data: { labels: baseInitialLabels.slice(), // 拷贝独立数组 datasets: [{ label: 'mAmpers', data: baseInitialData.slice(), // 拷贝独立数组 fill: false, backgroundColor: 'rgba(196, 34, 83, 0.8)', borderColor: 'rgba(196, 34, 83, 0.8)', borderWidth: 1, tension: 0.2 }] }, options: { scales: { y: { beginAtZero: true, max: 1.0 } } } }); // 功率图表初始化(同理) currentWattChart = new Chart(document.getElementById('wattageChart').getContext('2d'), { type: 'line', data: { labels: baseInitialLabels.slice(), datasets: [{ label: 'Watts', data: baseInitialData.slice(), fill: false, backgroundColor: 'rgba(34, 196, 83, 0.8)', borderColor: 'rgba(34, 196, 83, 0.8)', borderWidth: 1, tension: 0.2 }] }, options: { scales: { y: { beginAtZero: true } } } }); // 电压图表初始化(同理) currentVoltChart = new Chart(document.getElementById('voltageChart').getContext('2d'), { type: 'line', data: { labels: baseInitialLabels.slice(), datasets: [{ label: 'Voltage', data: baseInitialData.slice(), fill: false, backgroundColor: 'rgba(34, 83, 196, 0.8)', borderColor: 'rgba(34, 83, 196, 0.8)', borderWidth: 1, tension: 0.2 }] }, options: { scales: { y: { beginAtZero: true } } } });
2. 修正数据更新代码的错误
你当前的更新代码存在逻辑错误:更新电压数据时误操作了currentWattChart的data,需要确保只操作目标图表的对象:
console.log("Update for voltage: " + volt); // 仅操作电压图表的data和labels currentVoltChart.data.labels.pop(); currentVoltChart.data.datasets[0].data.pop(); currentVoltChart.data.labels.unshift('0'); currentVoltChart.data.datasets[0].data.unshift(volt); // 更新label文本 for(let i = 1; i < currentVoltChart.data.labels.length; i++) { currentVoltChart.data.labels[i] = `${-i}`; } currentVoltChart.update();
同理,更新电流或功率数据时,只需操作对应的currentAmpChart或currentWattChart即可。
额外优化:封装通用更新函数
可以封装重复逻辑,减少冗余代码:
function updateChart(chart, newData) { chart.data.labels.pop(); chart.data.datasets[0].data.pop(); chart.data.labels.unshift('0'); chart.data.datasets[0].data.unshift(newData); for(let i = 1; i < chart.data.labels.length; i++) { chart.data.labels[i] = `${-i}`; } chart.update(); } // 使用示例 updateChart(currentVoltChart, volt); // 更新电压 updateChart(currentAmpChart, amp); // 更新电流 updateChart(currentWattChart, watt); // 更新功率
内容的提问来源于stack exchange,提问作者bodo.00
相关产品推荐
相关产品推荐

