我正在寻找一种简单的解决方案,以在父div大小更改(=浏览器大小更改)后自动调整画布元素(图表)的大小。目前,我的Canvas元素仅在加载页面时完全适合父div。
到目前为止,这是我已经做过的事情,并且已经尝试过:
<div class="panel-body">
<canvas id="userlogins"></canvas>
<script type="text/javascript">
jQuery(document).ready(function($)
{
var ctx = $("#userlogins").get(0).getContext("2d");
var myLineChart = new Chart(ctx).Line(data, options);
});
function fitToContainer(canvas){
// Make it visually fill the positioned parent
canvas.style.width ='100%';
// ...then set the internal size to match
canvas.width = canvas.offsetWidth;
}
var canvas = document.querySelector('canvas');
fitToContainer(canvas);
jQuery( window ).resize(function() {
fitToContainer(canvas);
redraw();
});
</script>
</div>
调整浏览器大小时,画布图表会消失。父div适合页面加载效果很好。
编辑:给定的“重复项”中的方法对我不起作用!这是我从“重复问题”中给出的尝试:
jQuery( window ).resize(function() {
clearTimeout(timerID);
timerID = setTimeout(function() {
var cnvs = $("#userlogins")[0]; // cache canvas element
var rect = cnvs.getBoundingClientRect(); // actual size of canvas el. itself
cnvs.width = rect.width;
cnvs.height = rect.height;
redraw();
});
});
看起来您正在使用ChartJS。如果是,则它具有一个属性,您可以设置该属性以使图表响应于调整大小。
Chart.defaults.global.responsive = true;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句