首页 > 解决方案 > 如何为响应式站点动态调整 chart.js 图形的大小?

问题描述

嘿,我知道这已经以一种或另一种方式回答了很多次,但我真的无法让它在我的 flex-box 上下文中工作。

我有固定的元素,例如页面上的页眉和页脚,以及一个占据中间所有剩余空间的图表。虽然乍一看似乎可以正常工作,但您可以看到文本和数字在调整窗口大小时变得模糊且未正确缩放。

我该如何解决这个问题,或者让 chart.js 在调整大小时重绘画布?

看看我的小提琴 https://jsfiddle.net/fg9pd1b3/

<body>
  <div class="container">
    <div class="fixed">
      header
    </div>
    <div id="chartcontainer">
      <canvas id="chartJSContainer"></canvas>
    </div>
    <div class="fixed">
      footer
    </div>
  </div>
</body>

CSS:

html,
body {
  height: 100vh;
  min-height: 100vh;
  max-height: 100vh;
  margin: 0;
  padding: 0;
}

.container {
  width: 80%;
  height: 100%;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  flex-basis: 100%;
  flex-grow: 1;
  background: #CCC;
}

.p {
  text-align: center;
  font-size: 14px;
  padding-top: 140px;
}

.fixed {
  background: black;
  height: 100px;
  min-height: 100px;
  color: white;
  text-align: center;
}

#chartcontainer {
  position: relative;
  min-height: 200px;
  display: flex;
  flex-grow: 1;

}

canvas {
  width: 100% !important;
  height: 100% !important;
}

JS:

Chart.defaults.global.responsive = true;
var options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderWidth: 1
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderWidth: 1
      }
    ]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          reverse: false
        }
      }]
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);

标签: chartsresizechart.jsresponsive

解决方案


您已为画布 div 提供了固定的最小高度,这限制了图表进一步更改其尺寸。因此,以下代码自动将高度和宽度自动设置为 100%,从而提供灵活的图表。

#chartcontainer {
  position:relative;
  min-height:auto;
  width:100%;
  display: flex;
  flex-grow:1;
}

推荐阅读