Multi-layer canvas in Javascript

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var mainContext = document.getElementsById("canvas")[0].getContext("2d");

/* Create our layer's array */
var layers = [];

function addNewLayer(layers) {
/* Create the layer as a new canvas */
var layer = document.createElement("canvas");
var layerContext = layer1.getContext("2d");

/* Clear the canvas */
layerContext.clearRect(0, 0, 400, 200);

/* Add it to our layers array */
layers.push(layer);
}

We’ll create three layers, each one with a rectangle on it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/* Creates new layer and adds a rectangle to it */
var newLayer = addNewLayer(layers);
var newLayerContext = newLayer.getContext("2d");
newLayerContext.fillStyle = "#FF0000";
newLayerContext.fillRect(0, 0, 80, 100);

/* Creates new layer and adds a rectangle to it */
newLayer = addNewLayer(layers);
newLayerContext = newLayer.getContext("2d");
newLayerContext.fillStyle = "#00FF00";
newLayerContext.fillRect(10, 10, 80, 100);

/* Creates new layer and adds a rectangle to it */
newLayer = addNewLayer(layers);
newLayerContext = newLayer.getContext("2d");
newLayerContext.fillStyle = "#0000FF";
newLayerContext.fillRect(20, 20, 80, 100);

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
2
3
4
5
6
7
8
9
function drawImage(canvas, layers) {
var canvasContext = canvas.getContext("2d");
for(var i = 0; i < layers.lenght; i++ ) {
canvasContext.drawImage(layers[i], 0, 0);
}
}

/* On each change to the layers, draw the image again */
drawImage(mainCanvasContext, layers);

Here’s the code working: