教程 chartjs tutorial

响应式优化建议

使用 Chart.js 创建响应式图表时,合理设置画布大小和响应式参数至关重要。建议固定父容器尺寸,启用响应式选项,并针对高分辨率屏幕进行缩放处理,以确保图表清晰且布局稳定。

下面示例展示如何配置响应式画布和自适应尺寸。

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

const responsiveChart = new Chart(ctx, {
  type: "bar",
  data: {
    labels: ["一月", "二月", "三月", "四月", "五月"],
    datasets: [
      {
        label: "销售额",
        data: [50, 60, 70, 80, 90],
        backgroundColor: "rgba(54, 162, 235, 0.7)",
      },
    ],
  },
  options: {
    responsive: true,
    maintainAspectRatio: false,
    devicePixelRatio: window.devicePixelRatio || 1,
    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: 700px; margin: 2rem auto; font-family: sans-serif; background: #f9f9f9; padding: 1rem; text-align: center; }

#chartContainer {
  width: 100%;
  height: 400px;
  max-width: 700px;
  margin: 0 auto;
}

canvas {
  background: #fff;
  border: 1px solid #ccc;
  display: block;
  width: 100% !important;
  height: 100% !important;
}

</style> </head>

<body> <div id="chartContainer"> <canvas id="responsiveChart"></canvas> </div> <script> (function () { const ctx = document.getElementById(‘responsiveChart’).getContext(‘2d’);

  const responsiveChart = new Chart(ctx, {
    type: 'bar',
    data: {
      labels: ['一月', '二月', '三月', '四月', '五月'],
      datasets: [{
        label: '销售额',
        data: [50, 60, 70, 80, 90],
        backgroundColor: 'rgba(54, 162, 235, 0.7)'
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      devicePixelRatio: window.devicePixelRatio || 1,
      plugins: {
        legend: { display: true }
      }
    }
  });
})();

</script> </body>

</html>