主题
实时更新图表
在 Chart.js 中,通过周期性地修改数据并调用 update() 方法,可以实现实时更新图表的效果。这种方式广泛用于展示传感器数据、系统监控、用户行为数据等实时信息。
下面演示一个简单的实时折线图,每秒生成一个新点并追加到图表中,同时移除最旧的数据点,形成滚动式图表。
js
(function () {
const ctx = document.getElementById("liveChart").getContext("2d");
const labels = Array.from({ length: 10 }, (_, i) => `${i}s`);
const data = {
labels,
datasets: [
{
label: "实时数据",
data: Array.from({ length: 10 }, () => Math.random() * 100),
borderColor: "rgb(255, 99, 132)",
tension: 0.4,
},
],
};
const config = {
type: "line",
data,
options: {
responsive: true,
animation: false,
scales: {
y: {
min: 0,
max: 100,
},
},
},
};
const chart = new Chart(ctx, config);
setInterval(() => {
const newTime = `${parseInt(labels[labels.length - 1]) + 1}s`;
labels.push(newTime);
labels.shift();
chart.data.datasets[0].data.push(Math.random() * 100);
chart.data.datasets[0].data.shift();
chart.update();
}, 1000);
})();示例无法以 iframe 加载(请检查路径或将 demo 放到 public/)。