获取图表JS条形图以填充窗口 [英] Getting chart js bar chart to fill window

查看:72
本文介绍了获取图表JS条形图以填充窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a chart js bar chart that draws within the canvas:

<canvas id="chart" width="800" height="400"></canvas>

不过,我希望图表适合当前窗口的大小。我尝试过:

However I would like the chart to fit the size of the current window. I have tried:

<canvas id="chart" width="100%" height="400"></canvas>

但它不喜欢它。我可以使用window.innerWidth获取窗口宽度,但是有什么原因导致100%无法正常工作?

but it does not like it. I could get the window width using window.innerWidth but is there any reason why the 100% does not work?

推荐答案

请参阅帖子: Chart.js画布调整大小。实际上,这里有两个答案是非常好的解决方案。您可以使用如下所示的图表选项:

Please see the post: Chart.js canvas resize . There are actually two answers that are really good solutions here. You can use the chart options like below:

// 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,

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

or you can set the canvas width and height using client side code:

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

这篇文章非常有效地回答了您有关%值为何不起作用的问题:使用CSS时,画布会拉伸,而宽度 /高度属性

This post very effectively answers your question about why % values dont work: Canvas is stretched when using CSS but normal with "width" / "height" properties

这篇关于获取图表JS条形图以填充窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆