我正在尝试创建一个简单的游戏,但是我想知道如何在画布上实现3层,就像在photoshop中一样。我希望背景作为背景,透明的背景可以将背景反射到前景,而前景层将是主要的动画/渲染。这对性能有好处吗?另外,如何在这里实现三层结构?
的HTML
<div id ="container">
<canvas id = "canvas_background" width = "800" height = "500">
<canvas id = "canvas_trans" width = "800" height = "500">
<canvas id = "canvas_foreground" width = "800" height = "500">
</canvas>
</canvas>
</canvas>
</div>
的CSS
#container {
width: 800px;
margin: 20px auto;
height: 200px;
}
#canvas_background{
border: 1px solid #666;
position: absolute;
}
#canvas_trans{
position: absolute;
background-color: transparent;
z-index: 1;
}
#canvas_foreground{
position: absolute;
}
最佳答案
多个画布层绝对可以是good thing for performance!如果您的背景层只需要在每个场景中绘制一次,那么它允许您多次重绘前景,而不必担心浪费时间重绘背景。
但是,它们需要分层而不是嵌套。
<div id = "container" class = "container">
<canvas id = "canvas_background" width = "800" height = "500"></canvas>
<canvas id = "canvas_trans" width = "800" height = "500"></canvas>
<canvas id = "canvas_foreground" width = "800" height = "500"></canvas>
</div>
幸运的是,这对于CSS来说是微不足道的。我们可以使用绝对定位,并利用DOM元素默认情况下透明的事实。
.container {
position: relative;
}
.container > canvas {
position: absolute;
top: 0;
left: 0;
}
这会将所有画布元素设置为绝对位于容器元素内。
您需要记住的最后一件事是,要清除画布,必须使用
context.clearRect
方法,以便使画布恢复为透明状态,而不是用纯色填充。关于javascript - HTML5中的3层 Canvas ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28765227/