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

标签 chart.js

我有一个 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/

相关文章:

html - 如何删除到达我的网页的 CSS 代码?

javascript - 为什么使用对数给出 8e+2 值?

javascript - 如何在右中心对齐 Chart JS "legend"

javascript - 当值为 12 时,chart.js 雷达显示 0

html - 如何控制我的 Chart.JS 饼图图例的位置及其外观?

chart.js - Chartjs 2 缩放大量数据点

javascript - 在图表 js 中使标签响应

javascript - Chart.js:更改字体颜色和大小不起作用

javascript - 我可以修改或扩展 ChartJS 吗?

javascript - 将javascript转换为 Dart