将chart.js canvas置于容器中心,不添加缓冲区

ni65a41a  于 2023-05-06  发布在  Chart.js
关注(0)|答案(1)|浏览(132)

我正在尝试将Chart.js条形图居中,其中高度和宽度基于视口。
documentation明确指出以下方法不适用于<canvas style="margin: 0 auto;">。事实上,它使图形不断缩小,越来越小。
下面是我的代码:
HTML:

<div class="chart-container">
  <canvas id="myChart"</canvas>
</div>

CSS:

.chart-container {
  position: relative;
  margin: 0 auto;
  height: 70vh;
  width: 90vw;
}

Javascript:有一段Javascript代码,它获取元素并在in中创建一个new Chart。简化如下:

const element = document.getElementById('myChart');
  new Chart(element, {
    type: 'bar',
    data: {
      labels: ['one', 'two', 'three'],
      datasets: [{
        label: 'Alpha',
        data: [1, 2, 3]
      }]
    }
  });

我想父容器是相同的画布垂直大小(以避免在我的网页添加不必要的缓冲区)。
You can see here that as the screen becomes too wide and the height-based sizing takes effect, the chart is shoved to the left side of the chart-container
You can see here that as the screen becomes too long and the width-based sizing takes effect, the chart-container pushes down the next element, creating a large space gap

xdyibdwo

xdyibdwo1#

最后我使用了一些Javascript:

const chartContainers = Array.from(document.getElementsByClassName('chart-container'));
const chartMaxWidthPercent = 0.9;
const chartMaxHeightPercent = 0.7;

function resizeChartContainers() {
  let maxWidth = chartMaxHeightPercent * window.innerWidth;
  let maxHeight = chartMaxHeightPercent * window.innerHeight;
  let width = Math.min(maxWidth, maxHeight * 2);
  let height = Math.min(maxHeight, maxWidth / 2);
  chartContainers.forEach(container => {
    container.style.width=`${width}px`;
    container.style.height=`${height}px`;
  });
}

window.addEventListener("resize", resizeChartContainers);
resizeChartContainers(); // Initial resize

然后在我的CSS中,我删除了高度和宽度规范:

.chart-container {
  position: relative;
  margin: 0 auto;
}

相关问题