我有一个 chart js
在 Canvas 内绘制的条形图:
<canvas id="chart" width="800" height="400"></canvas>
但是我希望图表适合当前窗口的大小。我试过了:
<canvas id="chart" width="100%" height="400"></canvas>
但它不喜欢它。我可以使用 window.innerWidth 获取窗口宽度,但是 100% 不起作用有什么原因吗?
最佳答案
请看帖子:Chart.js canvas resize .实际上,这里有两个答案是非常好的解决方案。您可以使用如下图表选项:
// Boolean - whether or not the chart should be responsive and resize when the browser does.
responsive: true,
// Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
maintainAspectRatio: false,
或者您可以使用客户端代码设置 Canvas 宽度和高度:
var ctx = document.getElementById("canvas").getContext("2d");
ctx.canvas.width = 300;
ctx.canvas.height = 300;
var myDoughnut = new Chart(ctx).Doughnut(doughnutData);
这篇文章非常有效地回答了您关于为什么 % 值不起作用的问题:Canvas is stretched when using CSS but normal with "width" / "height" properties
关于chart.js - 获取图表js条形图以填充窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37026204/