教程 chartjs tutorial

渲染性能优化

在使用 Chart.js 时,尤其是处理大量数据或频繁更新图表时,性能优化显得尤为重要。合理减少重绘次数,禁用不必要的动画,以及分批更新数据,可以显著提升图表的渲染效率。

下面示例展示如何通过关闭动画和使用 update 方法的参数来优化性能。

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

const perfChart = new Chart(ctx, {
  type: "line",
  data: {
    labels: Array.from({ length: 1000 }, (_, i) => `点${i + 1}`),
    datasets: [
      {
        label: "大量数据",
        data: Array.from({ length: 1000 }, () => Math.random() * 100),
        borderColor: "rgb(75, 192, 192)",
        fill: false,
        tension: 0.1,
      },
    ],
  },
  options: {
    animation: false, // 关闭动画提升性能
    responsive: true,
    plugins: {
      legend: { display: true },
    },
  },
});

// 模拟数据更新但不重绘
setInterval(() => {
  perfChart.data.datasets[0].data = perfChart.data.datasets[0].data.map(
    () => Math.random() * 100
  );
  perfChart.update("none"); // 更新数据但不重绘动画
}, 2000);
在线代码演示
源码
<!DOCTYPE html>
<html lang="zh">

<head> <meta charset="UTF-8" /> <title>Chart.js 渲染性能优化示例</title> <script src="https://cdn.jsdelivr.net/npm/chart.js&quot;&gt;&lt;/script&gt; <style> body { max-width: 900px; margin: 2rem auto; font-family: sans-serif; background: #f9f9f9; padding: 1rem; text-align: center; }

canvas {
  background: #fff;
  border: 1px solid #ccc;
  margin: 1rem auto;
  max-width: 100%;
}

</style> </head>

<body> <canvas id="perfChart" width="900" height="400"></canvas> <script> (function () { const ctx = document.getElementById(‘perfChart’).getContext(‘2d’);

  const perfChart = new Chart(ctx, {
    type: 'line',
    data: {
      labels: Array.from({ length: 1000 }, (_, i) =&gt; `点${i + 1}`),
      datasets: [{
        label: '大量数据',
        data: Array.from({ length: 1000 }, () =&gt; Math.random() * 100),
        borderColor: 'rgb(75, 192, 192)',
        fill: false,
        tension: 0.1
      }]
    },
    options: {
      animation: false,
      responsive: true,
      plugins: {
        legend: { display: true }
      }
    }
  });

  setInterval(() =&gt; {
    perfChart.data.datasets[0].data = perfChart.data.datasets[0].data.map(() =&gt; Math.random() * 100);
    perfChart.update('none');
  }, 2000);
})();

</script> </body>

</html>