教程 chartjs tutorial

数据量大时的处理

当使用 Chart.js 展示大量数据时,性能和响应速度可能会下降。为了保证流畅的用户体验,可以采用数据简化、采样、分页加载或虚拟滚动等策略,减少图表一次性渲染的数据量。

以下示例演示如何通过采样减少数据点数,优化大数据量图表的显示效果。

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

// 模拟原始数据,10000个点
const rawData = Array.from({ length: 10000 }, () => Math.random() * 100);

// 简单采样:每隔10个点取一个
const sampledData = rawData.filter((_, i) => i % 10 === 0);

const bigDataChart = new Chart(ctx, {
  type: "line",
  data: {
    labels: sampledData.map((_, i) => `点${i + 1}`),
    datasets: [
      {
        label: "采样数据",
        data: sampledData,
        borderColor: "rgb(255, 99, 132)",
        fill: false,
        tension: 0.1,
      },
    ],
  },
  options: {
    responsive: true,
    animation: false,
    plugins: {
      legend: { display: true },
    },
  },
});
在线代码演示
源码
<!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="bigDataChart" width="900" height="400"></canvas> <script> (function () { const ctx = document.getElementById(‘bigDataChart’).getContext(‘2d’);

  const rawData = Array.from({ length: 10000 }, () =&gt; Math.random() * 100);

  const sampledData = rawData.filter((_, i) =&gt; i % 10 === 0);

  const bigDataChart = new Chart(ctx, {
    type: 'line',
    data: {
      labels: sampledData.map((_, i) =&gt; `点${i + 1}`),
      datasets: [{
        label: '采样数据',
        data: sampledData,
        borderColor: 'rgb(255, 99, 132)',
        fill: false,
        tension: 0.1
      }]
    },
    options: {
      responsive: true,
      animation: false,
      plugins: {
        legend: { display: true }
      }
    }
  });
})();

</script> </body>

</html>