DEMO Here’s our finished canvas with full source code.
The reasons why you would want to layer multiple canvases on top of each other are many but they all have a common root. There is a requirement in the W3C definition of the 2d context…
There is only one CanvasRenderingContext2D object per canvas, so calling the getContext() method with the 2d argument a second time must return the same object.
Having just one 2d context means that you have to keep track of everything on the context even if you only want to change part of the canvas.
An example of using layers is animation. When I was a child, I loved making animated cartoons and I learned that if I painted them on clear plastic sheets I could stack the sheets and only redraw the parts that moved. I could make an elaborate background and use it over and over instead of redrawing it for every frame. The same principle applies here to our canvases.
In this example, our three canvases have transparent areas that allow you to see what is on the canvas beneath each.
First, let’s look at our three canvases separately and then we’ll stack them on top of each other.
Our bottom layer
Our middle layer
Our top layer
Now to stack them
We use CSS to set all the canvases to an absolute position of (0,0) inside our parent DIV tag.
position:absolute; left:0px; top:0px;
We also use CSS to set the z-index of our canvases. The z-index property specifies the stack order of an element. Items with lower z-index values go behind items with higher z-index values.
Bottom layer canvas id="layer1" style="z-index: 1; Middle layer canvas id="layer2" style="z-index: 2; Top Layer canvas id="layer3" style="z-index: 3;
DEMO Here's our finished canvas with full source code.
Now it doesn't matter that a canvas can only have one 2d context because we can just make multiple canvases and stack them.
If you have a question that you do not want published as a public comment, then use my contact page.
Have fun with the code as that is the easiest way to learn.