教程 chartjs tutorial

定时刷新图表

使用定时器可以让 Chart.js 图表定期更新数据,适合实时监控和动态展示需求。通过定时请求接口并调用 chart.update(),保证图表数据同步最新。

以下示例每隔 3 秒模拟更新图表数据,实现自动刷新效果。

js
const ctx = document.getElementById("refreshChart").getContext("2d");

const refreshChart = new Chart(ctx, {
  type: "bar",
  data: {
    labels: ["一月", "二月", "三月", "四月", "五月"],
    datasets: [
      {
        label: "销售额",
        data: [12, 19, 3, 5, 2],
        backgroundColor: "rgba(54, 162, 235, 0.7)",
      },
    ],
  },
  options: {
    responsive: true,
    plugins: {
      legend: { display: true },
    },
  },
});

setInterval(() => {
  // 模拟数据更新
  refreshChart.data.datasets[0].data = refreshChart.data.datasets[0].data.map(
    () => Math.floor(Math.random() * 30)
  );
  refreshChart.update();
}, 3000);
在线代码演示
源码
<!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="refreshChart" width="700" height="400"></canvas> <script> (function () { const ctx = document.getElementById(‘refreshChart’).getContext(‘2d’);

  const refreshChart = new Chart(ctx, {
    type: 'bar',
    data: {
      labels: ['一月', '二月', '三月', '四月', '五月'],
      datasets: [{
        label: '销售额',
        data: [12, 19, 3, 5, 2],
        backgroundColor: 'rgba(54, 162, 235, 0.7)'
      }]
    },
    options: {
      responsive: true,
      plugins: {
        legend: { display: true }
      }
    }
  });

  setInterval(() =&gt; {
    // 模拟数据更新
    refreshChart.data.datasets[0].data = refreshChart.data.datasets[0].data.map(() =&gt;
      Math.floor(Math.random() * 30)
    );
    refreshChart.update();
  }, 3000);
})();

</script> </body>

</html>