画布未正确调整为div(滚动条问题??)

时间:2013-03-28 20:08:58

标签: javascript canvas resize scroll

我不知道是否有人注意到这一点,但我会试一试。

因为画布的行为与其他HTML元素不同,所以我使用resize事件来调整它的大小而不是CSS。这很有效,

除非将浏览器从最大化调整为正常,在这种情况下画布小于div。差异在于

滚动条的宽度。事实上,当我使画布大到足以强制执行滚动条时,这不会发生。

这与调整大小事件的时间有关吗?有人知道怎么解决吗?

修改

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();
}

1 个答案:

答案 0 :(得分:2)

使用getBoundingClientRect获取宽度和高度,并使画布大小。

<强> Live Demo

Full Screen

标记

<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);
}