I’m trying to create a simple game, but I’m wondering how to implement 3 layered in canvas, somehow like in a photoshop. I want the background to be as background, the transparent one would be something it can reflect the background to the foreground and foreground layer would be the main animations/rendering. Will that be a good point for performance? Also, how to implement the 3 layered structure here?
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;
}
2
Answers
Multiple canvas layers can definitely be a good thing for performance! If your background layer only needs to be drawn once each scene, then it allows you to redraw your foreground lots of times, without having to worry about wasting time redrawing the background.
However, they need to be layered rather than nested.
Thankfully, this is trivial with CSS. We can use absolute positioning and take advantage of the fact that DOM elements are transparent by default.
This will set all canvas elements to be absolutely positioned within the container element.
The last thing you’ll need to remember is that to clear the canvases, you’ll have to use the
context.clearRect
method, in order to return the canvas to transparency, rather than filling it with a solid colour.I would suggest to handle this in your logic : do three functions, it is less ressource intensive, and more maintainable, if you need more “layers” just create new functions. Don’t mess your dom up.
In each of them, you draw only the items of that layer you can set the transparency of an image by setting the globalAlpha parameter BEFORE you draw the image. For shapesn use
for example.