获取图表js条形图以填充窗口

RGr*_*ths 4 chart.js

我有一个chart js在画布内绘制的条形图:

<canvas id="chart" width="800" height="400"></canvas>
Run Code Online (Sandbox Code Playgroud)

但是我希望图表适合当前窗口的大小。我试过了:

<canvas id="chart" width="100%" height="400"></canvas>
Run Code Online (Sandbox Code Playgroud)

但它不喜欢它。我可以使用 window.innerWidth 获取窗口宽度,但是 100% 不起作用有什么原因吗?

MUl*_*rts 8

请参阅帖子: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,
Run Code Online (Sandbox Code Playgroud)

或者您可以使用客户端代码设置画布宽度和高度:

var ctx = document.getElementById("canvas").getContext("2d");
ctx.canvas.width = 300;
ctx.canvas.height = 300;
var myDoughnut = new Chart(ctx).Doughnut(doughnutData);
Run Code Online (Sandbox Code Playgroud)

这篇文章非常有效地回答了您关于为什么 % 值不起作用的问题:使用 CSS 时画布被拉伸,但具有“宽度”/“高度”属性是正常的