-3

我正在尝试将 HTML5 画布作为我网页的背景。无论我做什么,我都无法让它工作。有谁知道怎么做?这是我目前的尝试:

<!DOCTYPE html>
<html>

<head> <title> Test </title> </head>

<style>
    #bgcanvas {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index = -1;
    }
</style>


<script type="text/javascript">
    function fillCanvas(){
        var bg = document.getElementById("bgcanvas");
        var ctx = bg.getContext("2d");
        ctx.fillStyle = "#00FF00";
        ctx.fillRect(0, 0, 50, 50);

        ctx = document.getElementById("screen").getContext("2d");
        ctx.fillStyle = "#0000FF";
        ctx.fillRect(0, 0, 500, 400);
    }
</script>

<body onload="fillCanvas();">
<center>

    <h1>Test Page</h1>


    <canvas id="screen" width=720 height=480 style="background: black;">
        Your browser sucks. Please upgrade.
    </canvas>

</center>
</body>

<canvas id="bgcanvas" width=100 height=100> </canvas>


</html>

谢谢!

4

1 回答 1

0

这里有一些简单的错误,您可以调整以使其工作,如各种评论中指出的那样:

#bgcanvas {
    /* ... rest not shown ... */
    /* remove these unless you want the content to scale like an image:
    width: 100%;
    height: 100%;
    */
    z-index: -1; /* change = to :. = is not supported in CSS for properties */
}

在 body 标签移动 canvas 元素:

    ...
    <canvas id="bgcanvas" width=100 height=100> </canvas>
</body>

提示:增加大小以获得更好的质量(您当前将 100x100 像素的“图像”缩放到大约窗口大小,这可能会产生较差的结果)。

您也可以在向其绘制任何内容之前,在脚本中以这种方式删除 CSS 大小并设置画布大小:

var bg = document.getElementById("bgcanvas");
bg.width = window.innerWidth;
bg.height = window.innerHeight;
于 2013-09-20T20:28:43.477 回答