javascript screen.width和screen.height无法按预期呈现

时间:2012-10-28 13:22:54

标签: javascript html google-chrome html5-canvas render

尝试使元素呈现屏幕的完整大小:

<!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>

但是canvas元素在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";

将其设置为镀铬的屏幕尺寸,然后检查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上做过这个,但我使用了jQuery css({width:screen.width, height:screen.height})来设置它,这就是为什么它有效但我不明白为什么这种方式在chrome中不起作用。< / p>

3 个答案:

答案 0 :(得分:2)

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

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

Css风格搞砸了

答案 1 :(得分:0)

尝试设置

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

没有.style.

答案 2 :(得分: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";