教程 chartjs tutorial

实时温度监控

通过使用 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);
在线代码演示
源码
<!DOCTYPE html>
<html lang="zh">

<head> <meta charset="UTF-8" /> <title>实时温度监控示例</title> <script src="https://cdn.jsdelivr.net/npm/chart.js&quot;&gt;&lt;/script&gt; <style> body { max-width: 700px; margin: 2rem auto; font-family: sans-serif; background: #f9f9f9; padding: 1rem; text-align: center; }

canvas {
  background: #fff;
  border: 1px solid #ccc;
  width: 100% !important;
  height: 300px !important;
  margin: 0 auto;
}

</style> </head>

<body> <canvas id="tempChart"></canvas> <script> (function () { 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: { y: { min: 0, max: 50 } }, plugins: { legend: { display: true } } } });

  // 模拟实时数据,每秒更新一次
  setInterval(() =&gt; {
    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 &gt; 20) {
      tempChart.data.labels.shift();
      tempChart.data.datasets[0].data.shift();
    }
    tempChart.update();
  }, 1000);
})();

</script> </body>

</html>