主题
实时温度监控
通过使用 Chart.js 动态更新数据,可以实现实时温度监控。以下示例展示了一个折线图,模拟每秒获取最新温度并更新图表。
js
const ctx = document.getElementById('tempChart').getContext('2d');
const tempChart = new Chart(ctx, {
type: 'line',
data: {
labels: [],
datasets: [{
label: '温度 (℃)',
data: [],
borderColor: 'rgb(255, 99, 132)',
fill: false,
tension: 0.3
}]
},
options: {
responsive: true,
animation: false,
scales: {
x: { type: 'realtime', realtime: { delay: 2000 } },
y: { min: 0, max: 50 }
},
plugins: {
legend: { display: true }
}
}
});
// 模拟实时数据,每秒更新一次
setInterval(() => {
const now = new Date().toLocaleTimeString();
const temp = 20 + Math.random() * 10;
tempChart.data.labels.push(now);
tempChart.data.datasets[0].data.push(temp);
if (tempChart.data.labels.length > 20) {
tempChart.data.labels.shift();
tempChart.data.datasets[0].data.shift();
}
tempChart.update();
}, 1000);
loading