Javascript 为什么将HTML5画布放在背景中并不';不行?

Javascript 为什么将HTML5画布放在背景中并不';不行?,javascript,html,canvas,html5-canvas,Javascript,Html,Canvas,Html5 Canvas,我试图把HTML5画布作为我的网页背景。不管我做什么,我都不能让它工作。有人知道怎么做吗?这是我目前的尝试: <!DOCTYPE html> <html> <head> <title> Test </title> </head> <style> #bgcanvas { position: fixed; top: 0; left: 0; w

我试图把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{
位置:固定;
排名:0;
左:0;
宽度:100%;
身高:100%;
z指数=-1;
}
函数fillCanvas(){
var bg=document.getElementById(“bgcanvas”);
var ctx=bg.getContext(“2d”);
ctx.fillStyle=“\35; 00FF00”;
ctx.fillRect(0,0,50,50);
ctx=document.getElementById(“屏幕”).getContext(“2d”);
ctx.fillStyle=“#0000FF”;
ctx.fillRect(0,0500400);
}
测试页
你的浏览器糟透了。请升级。

谢谢

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

#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 */
}
在主体标记内移动画布元素:

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

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

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

您的画布元素在主体之外,tagz索引不能为负,并且您在CSS中不使用“=”。修复CSS
=
,它就会工作。但是修复无效的html也很好。。。另外,请注意,使用CSS缩放画布也会缩放其内容。@Douglas“框可能具有负堆栈级别。”@Ken:啊,是的,你说得对。这很尴尬。我没有注意到我使用了=,这太愚蠢了。我很抱歉为这样一个愚蠢的错误浪费了大家的时间。另外,画布是在外面的,因为我正在测试如何在文档中移动它。非常抱歉@理查德:这可能发生在任何人身上