1

试图让一个元素呈现屏幕的全尺寸:

<!DOCTYPE html>
<html>
<head>
    <title>Test Page</title>
</head>
<body>
    <canvas></canvas>
    <script>
        (function(){
            var canvas = document.getElementsByTagName("canvas")[0];
            canvas.style.background = "#0f0";
            canvas.style.width = screen.width + "px";
            canvas.style.height = screen.height + "px";

            console.log(
                "screen.width: " + screen.width +
                "\nscreen.height: " + screen.height +
                "\ncanvas.width: " + canvas.style.width +
                "\ncanvas.height: " + canvas.style.height
            );
        })()
    </script>
</body>
</html>

但是画布元素在 chrome v22 中以大约两倍的宽度和两倍的高度呈现,但在 FF 中似乎很好。我得到控制台输出:

screen.width:1366 screen.height:768 canvas.width:1366px canvas.height:768px

如果我在 chrome 中手动设置画布的宽度和高度,我必须使用:

canvas.style.width = 780 + "px";
canvas.style.height = 435 + "px";

使其达到 chrome 中的屏幕大小,然后检查 FF,这按预期呈现在两个维度上都略高于屏幕的一半。

更新:

我试过这个:

<!DOCTYPE html>
<html>
<head>
    <title>Test Page</title>
</head>
<body style="padding:0;margin:0;">
    <div>
        <canvas>
        </canvas>
    </div>
    <script>
        (function(){
            var div = document.getElementsByTagName("div")[0],
                canvas = document.getElementsByTagName("canvas")[0];

            div.style.background = "#f00";
            div.style.width = screen.width + "px";
            div.style.height = screen.height + "px";

            canvas.style.background = "#0f0";
            canvas.style.width = "100%";
            canvas.style.height = "100%";

            console.log(
                "screen.width: " + screen.width +
                "\nscreen.height: " + screen.height +
                "\ncanvas.width: " + canvas.style.width +
                "\ncanvas.height: " + canvas.style.height
            );
        })()
    </script>
</body>
</html>

但它具有相同的效果,适用于 FF 但不适用于 chrome。

我之前在我的测试站点 www.0xor1.com 上做过这个,但我使用 jQuerycss({width:screen.width, height:screen.height})来设置它,这就是它工作的原因,但我不明白为什么这种方式在 chrome 中不起作用。

4

3 回答 3

2

画布元素的宽度和高度应标记为:

<canvas id="myCanvas" width="200" height="200">

Css 样式搞砸了

于 2012-10-28T13:28:42.970 回答
0

尝试设置

canvas.width = screen.width + "px";
canvas.height = screen.height + "px";

没有.style.

于 2012-10-28T13:28:50.163 回答
0

也许你的窗口比你的屏幕小得多。你不能覆盖比窗户更多的东西,所以也许屏幕不是你想要的。

如果把它改成这样,它就会覆盖整个身体

        var canvas = document.getElementsByTagName("canvas")[0];
        var body = document.getElementsByTagName("body")[0];
        canvas.style.background = "#0f0";
        canvas.style.width = body.offsetWidth + "px";
        canvas.style.height = body.offsetHeight + "px";
于 2012-10-28T13:28:54.610 回答