# 实时温度监控

URL: https://caijiao.org/chartjs/10-projects/03-temperature-monitor
Source: docs/chartjs/10-projects/03-temperature-monitor.md
Description: 展示一个实时温度监控图表示例，使用折线图动态更新温度数据，适合监测环境变化。

通过使用 [Chart.js](/chartjs/) 动态更新数据，可以实现实时温度监控。以下示例展示了一个折线图，模拟每秒获取最新温度并更新图表。

```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);
```

[在线代码演示](/chartjs/demos/35.html)
