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.
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.
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:
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 thelayer2
canvas. Then when youclearRect
on the top layer, whatever's on the lower canvas will show through.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.
I understand that the Q does not want to use a library, but I will offer this for others coming from Google searches. @EricRowell mentioned a good plugin, but, there is also another plugin you can try, html2canvas.
In our case we are using layered transparent PNG's with
z-index
as a "product builder" widget. Html2canvas worked brilliantly to boil the stack down without pushing images, nor using complexities, workarounds, and the "non-responsive" canvas itself. We were not able to do this smoothly/sane with the vanilla canvas+JS.First use
z-index
on absolute divs to generate layered content within a relative positioned wrapper. Then pipe the wrapper through html2canvas to get a rendered canvas, which you may leave as-is, or output as an image so that a client may save it.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
oncontext
.Example:
And here is some codepen: https://codepen.io/anon/pen/mQWMMW
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.