为什么将HTML5画布放在后台不起作用

Why putting HTML5 canvas into the background doesn't work?

本文关键字:后台 不起作用 布放 HTML5 为什么      更新时间:2023-09-26

我正在尝试将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>

谢谢!

这里有一些简单的错误,您可以调整以使其工作,如各种注释中所述:

#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 */
}

将画布元素移动到正文标签

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

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

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

var bg = document.getElementById("bgcanvas");
bg.width = window.innerWidth;
bg.height = window.innerHeight;