我不知道是否有人注意到这一点,但我会尝试一下。
由于 Canvas 的行为与其他 HTML 元素不同,因此我使用 resize 事件而不是 CSS 来调整其大小。这个效果很好,
除非浏览器大小从最大化调整为正常,在这种情况下 Canvas 小于 div。差别大约是
滚动条的宽度。事实上,当我将 Canvas 设置得足够大以强制使用滚动条时,这种情况就不会发生。
这与调整大小事件的时间有关吗?有谁知道怎么解决吗?
编辑
这对于 IE9(右侧)和 Safari(底部和右侧)来说是正确的。但不适用于 Chrome 和 FF。
在这里摆弄 -> fiddle
/编辑
window.onload = function()
{
canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
window.addEventListener('resize', doTheResize, false);
}
function doTheResize()
{
canvas.width = div.clientWidth;
canvas.height = div.clientHeight;
drawThings();
}
最佳答案
使用getBoundingClientRect获取宽度和高度并使 Canvas 达到该尺寸。
<强> Live Demo
标记
<div class="container">
<canvas id="canvas"></canvas>
</div>
CSS
html, body {
width:100%;
height:100%;
padding:0;
margin:0;
}
.container {
height:100%;
width:600px;
}
JS
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d");
canvas.width = canvas.parentNode.getBoundingClientRect().width;
canvas.height = canvas.parentNode.getBoundingClientRect().height;
ctx.fillRect(0, 0, canvas.width, canvas.height);
window.onresize = function () {
canvas.width = canvas.parentNode.getBoundingClientRect().width;
canvas.height = canvas.parentNode.getBoundingClientRect().height;
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
关于javascript - Canvas 未根据 div 正确调整大小(滚动条问题??),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15691221/