我正在尝试将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>
谢谢!
答案 0 :(得分: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 */
}
将canvas元素移动到 body标记内:
...
<canvas id="bgcanvas" width=100 height=100> </canvas>
</body>
提示:增加尺寸以获得更好的质量(您目前将100x100像素的“图像”缩放到大约窗口的大小,这会导致效果不佳)。
您可以在绘制任何内容之前删除CSS大小调整并在脚本中以这种方式设置画布大小:
var bg = document.getElementById("bgcanvas");
bg.width = window.innerWidth;
bg.height = window.innerHeight;