Chart.js插件的canvas大小问题

韦阳辉
2023-12-01

Detecting when the canvas size changes can not be done directly from the CANVAS element. Chart.js uses its parent container to update the canvas render and display sizes. However, this method requires the container to be relatively positioned and dedicated to the chart canvas only. Responsiveness can then be achieved by setting relative values for the container size (example):

如果要设置图表大小,需要在<canvas>标签外面添加<div>,并设置"position: relative",因为Chart.js不能从canvas获取宽度来生成<iframe>,同时生成的<iframe>是绝对定位"position: absolution"。

<div class="chart-container" style="position: relative; height:40vh; width:80vw">
    <canvas id="chart"></canvas>
</div>

The chart can also be programmatically resized by modifying the container size:

chart.canvas.parentNode.style.height = '128px';

 

 类似资料: