Multi layer drawings can be useful for animations and graphical applications.
How simple is to implement a fast drawing multi layered canvas? Pretty easy:
First of all, we need a canvas in the HTML page to see what’s going on.
This will be our main canvas, where all the layers will merge to form the image.
1 | <canvas id="myCanvas" width="400" height="200" style="border:1px solid #000000;"> |
Now, for each layer, we’ll use a new canvas, each canvas will allow as to draw freely, creating a new image that will be later drawn in the main canvas. We’ll create the function addNewLayer() that will create a new canvas, and push it to our layers array.
The layers transparency is assured due to the clearRect() function, if this is not called each layer will end up placing a black background at the time of fusing the layers.
1 | var mainContext = document.getElementsById("canvas")[0].getContext("2d"); |
We’ll create three layers, each one with a rectangle on it.
1 | /* Creates new layer and adds a rectangle to it */ |
We have now our layering system and our three layers drawn, let’s draw them to the main canvas.
We’ll create a drawImage() function that will draw each layer on top of the other in our main canvas. Each time we make a change on a layer it is necessary to re-write the layers again to make the changes visible again.
1 | function drawImage(canvas, layers) { |
Here’s the code working: