教程 chartjs tutorial

尺寸与响应式

在使用 Chart.js 创建图表时,合理设置尺寸和响应式选项非常重要。Chart.js 支持自动响应容器大小,也可以通过配置固定宽高来控制图表尺寸,帮助适配各种屏幕和布局需求。

js
(function () {
  const ctx = document.getElementById("responsiveChart").getContext("2d");
  const responsiveChart = new Chart(ctx, {
    type: "bar",
    data: {
      labels: ["红", "蓝", "黄", "绿", "紫", "橙"],
      datasets: [
        {
          label: "示例数据",
          data: [12, 19, 3, 5, 2, 3],
          backgroundColor: [
            "rgba(255, 99, 132, 0.7)",
            "rgba(54, 162, 235, 0.7)",
            "rgba(255, 206, 86, 0.7)",
            "rgba(75, 192, 192, 0.7)",
            "rgba(153, 102, 255, 0.7)",
            "rgba(255, 159, 64, 0.7)",
          ],
        },
      ],
    },
    options: {
      responsive: true, // 图表自动响应容器大小
      maintainAspectRatio: false, // 是否维持宽高比,false 时可自定义高度
      plugins: {
        legend: { display: true },
        tooltip: { enabled: 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: Arial, sans-serif; background: #fafafa; padding: 1rem; }

#chart-container {
  position: relative;
  height: 400px;
  /* 设置容器高度以测试响应式 */
  width: 100%;
  background: #fff;
  border: 1px solid #ccc;
  margin: 0 auto;
}

canvas {
  /* 画布会自动填满容器 */
}

</style> </head>

<body> <div id="chart-container"> <canvas id="responsiveChart"></canvas> </div> <script> (function () { const ctx = document.getElementById(‘responsiveChart’).getContext(‘2d’); new Chart(ctx, { type: ‘bar’, data: { labels: [‘红’, ‘蓝’, ‘黄’, ‘绿’, ‘紫’, ‘橙’], datasets: [{ label: ‘示例数据’, data: [12, 19, 3, 5, 2, 3], backgroundColor: [ ‘rgba(255, 99, 132, 0.7)’, ‘rgba(54, 162, 235, 0.7)’, ‘rgba(255, 206, 86, 0.7)’, ‘rgba(75, 192, 192, 0.7)’, ‘rgba(153, 102, 255, 0.7)’, ‘rgba(255, 159, 64, 0.7)’ ] }] }, options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: true }, tooltip: { enabled: true } } } }); })(); </script> </body>

</html>