html5 - canvas element - Multiple layers

Gregoire picture Gregoire · Jun 9, 2010 · Viewed 201.2k times · Source

Without any extension library, is it possible to have multiple layers in the same canvas element?

So if I do a clearRect on the top layer, it will not erase the bottom one?

Thanks.

Answer

jimr picture jimr · Jun 9, 2010

No, however, you could layer multiple <canvas> elements on top of each other and accomplish something similar.

<div style="position: relative;">
 <canvas id="layer1" width="100" height="100" 
   style="position: absolute; left: 0; top: 0; z-index: 0;"></canvas>
 <canvas id="layer2" width="100" height="100" 
   style="position: absolute; left: 0; top: 0; z-index: 1;"></canvas>
</div>

Draw your first layer on the layer1 canvas, and the second layer on the layer2 canvas. Then when you clearRect on the top layer, whatever's on the lower canvas will show through.