html5 - canvas element - Multiple layers

how to use multiple canvas in html5
html5 canvas layers transparency
html5 canvas z-index
xml html5 canvas element
canvas performance
html5 canvas draw multiple rectangles
html5 canvas resources
how to position canvas in html5

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.

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.

Optimize HTML5 canvas rendering with layering – IBM Developer, The <canvas> element is one of the most widely used tools for rendering 2D graphics on Use multiple layered canvases for complex scenes. Now that you know how to implement the example using a single canvas, let’s find ways to refine this type of scene and speed up the render loop. To use the layer technique, you have to identify the HTML5 canvas elements the layering needs by finding the entities’ rendering overlap.

Related to this:

If you have something on your canvas and you want to draw something at the back of it - you can do it by changing the context.globalCompositeOperation setting to 'destination-over' - and then return it to 'source-over' when you're done.

   var context = document.getElementById('cvs').getContext('2d');

    // Draw a red square
    context.fillStyle = 'red';
    context.fillRect(50,50,100,100);



    // Change the globalCompositeOperation to destination-over so that anything
    // that is drawn on to the canvas from this point on is drawn at the back
    // of what's already on the canvas
    context.globalCompositeOperation = 'destination-over';



    // Draw a big yellow rectangle
    context.fillStyle = 'yellow';
    context.fillRect(0,0,600,250);


    // Now return the globalCompositeOperation to source-over and draw a
    // blue rectangle
    context.globalCompositeOperation = 'source-over';

    // Draw a blue rectangle
    context.fillStyle = 'blue';
    context.fillRect(75,75,100,100);
<canvas id="cvs" />

Using Multiple HTML5 Canvases as Layers – Unknown Kadath, HML5 Canvas Tutorial : The basics of HTML 5 canvas which provides an easy A webpage may contain multiple canvas elements. two layers on a Canvas element and CSS Canvas Drawings - Method of using HTML5  Back to the article Using Multiple HTML5 Canvases as Layers Here's the source code. This example is coded for readability and not for optimized operation. All you need is a text editor like notepad, a copy of the image city.png (rightclick and save it) and an HTML5 friendly browser (I'm using Firefox 3.6).

You can create multiple canvas elements without appending them into document. These will be your layers:

Then do whatever you want with them and at the end just render their content in proper order at destination canvas using drawImage on context.

Example:

/* using canvas from DOM */
var domCanvas = document.getElementById('some-canvas');
var domContext = domCanvas.getContext('2d');
domContext.fillRect(50,50,150,50);

/* virtual canvase 1 - not appended to the DOM */
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'blue';
ctx.fillRect(50,50,150,150);

/* virtual canvase 2 - not appended to the DOM */    
var canvas2 = document.createElement('canvas')
var ctx2 = canvas2.getContext('2d');
ctx2.fillStyle = 'yellow';
ctx2.fillRect(50,50,100,50)

/* render virtual canvases on DOM canvas */
domContext.drawImage(canvas, 0, 0, 200, 200);
domContext.drawImage(canvas2, 0, 0, 200, 200);

And here is some codepen: https://codepen.io/anon/pen/mQWMMW

Optimizing canvas, An existing canvas element becomes the background layer to the canvas stack. Multiple CanvasStack instances can be created that refer to the same  An html5 canvas with multiple layers. GitHub Gist: instantly share code, notes, and snippets.

I was having this same problem too, I while multiple canvas elements with position:absolute does the job, if you want to save the output into an image, that's not going to work.

So I went ahead and did a simple layering "system" to code as if each layer had its own code, but it all gets rendered into the same element.

https://github.com/federicojacobi/layeredCanvas

I intend to add extra capabilities, but for now it will do.

You can do multiple functions and call them in order to "fake" layers.

HTML5 Canvas Tutorial for beginners, This page contains an excellent list of optimizations that can be made to canvas. In the section labeled "Use multiple layered canvases for  The canvas is initially blank. To display something, a script first needs to access the rendering context and draw on it. The <canvas> element has a method called getContext (), used to obtain the rendering context and its drawing functions. getContext () takes one parameter, the type of context.

You might also checkout http://www.concretejs.com which is a modern, lightweight, Html5 canvas framework that enables hit detection, layering, and lots of other peripheral things. You can do things like this:

var wrapper = new Concrete.Wrapper({
  width: 500,
  height: 300,
  container: el
});

var layer1 = new Concrete.Layer();
var layer2 = new Concrete.Layer();

wrapper.add(layer1).add(layer2);

// draw stuff
layer1.sceneCanvas.context.fillStyle = 'red';
layer1.sceneCanvas.context.fillRect(0, 0, 100, 100);

// reorder layers
layer1.moveUp();

// destroy a layer
layer1.destroy();

Canvas Layers, canvas element per layer. This tutorial has two layers, one layer that's animated, and another static layer that contains text. Since there's no  HTML5. Canvas. Previous Next . Your browser does not support the <canvas> element. The HTML <canvas> element is used to draw graphics on a web page. The graphic to the left is created with <canvas>. It shows four elements: a red rectangle, a gradient rectangle, a multicolor rectangle, and a multicolor text.

Is using multiple canvas objects a good practice?, When I created my first HTML5 game I was surprised that the canvas element in HTML5 didn't support multiple layers that could be painted on  A possible optimization in this situation is to layer your items using multiple <canvas> elements. For example, let's say you have a game with a UI on top, the gameplay action in the middle, and a static background on the bottom. In this case, you could split your game into three <canvas> layers. The UI would change only upon user input, the gameplay layer would change with every new frame, and the background would remain generally unchanged.

HTML5 Canvas Layer Management Performance Tip, div.offset().left+'px'. });. var layer=$.extend(true,{. canvas:$canvas[0],. visible:true,. // Objects to be displayed on the canvas. // (each one requires a draw function  No, however, you could layer multiple <canvas> elements on top of each other and accomplish something similar. 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. Thanks for your answer.

Stratiscape, In the above code snippet we have defined the layers in the canvas We have created the canvas element id as mycanvas and width value 250, height value 200 In the script function we are calling the window.addeventlistener as the function load, we have given the var canvas id as mycanvas and context as canvas

Comments
  • you may want to take a look at radikalfx.com/2009/10/16/canvas-collage. he uses a sort of "layers" technique.
  • check this out.. html5.litten.com/using-multiple-html5-canvases-as-layers this will help you to resolve your issue in proper way
  • @Dakshika Thank you for that link, it explained a problem I had using the canvas a few years ago that a library took care of for me.
  • is there a way of hiding/unhiding a layer.. such that i can hide layer1 and show layer2 and do vice-versa when required..??
  • You could hide it with CSS - i.e display: none;. Or just clear the canvas, if it's not super expensive to redraw it again when the layer should be shown.
  • The values assigned to 'left' and 'top' need to be '0px', not '0'.
  • @BryanGreen Not true. "However, for zero lengths the unit identifier is optional (i.e. can be syntactically represented as the <number> 0)." w3.org/TR/css3-values/#lengths
  • Can I control the composition type for multiple canvas?
  • yes, that is fine but in case of erasing, as asked in question. this will erase both layers parallelly. which is again not correct.
  • @SCLeo you said "Performance killer. About ~10 times slower" is completely wrong. Depending on use cases using a single DOM canvas and rendering offscreen canvases to that is quicker than stacking canvas in DOM. The common mistake is benchmarking rendering calls, canvas draw calls can be timed, DOM rendering is outside Javascripts context and can not be timed. The result is that the be DOM stacked canvas do not get the compositing render (done by DOM) included in the benchmark..