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';

本文介绍了如何使用Chart.js创建响应式图表,包括通过外部div容器设置canvas尺寸的方法及程序化调整图表大小的技术细节。
868





