教程 chartjs tutorial

实时更新图表

在 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);
})();
在线代码演示
源码
<!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;
  margin: 1rem auto;
}

</style> </head>

<body> <canvas id="liveChart" width="700" height="400"></canvas> <script> (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(() =&gt; {
    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);
})();

</script> </body>

</html>