Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to layer in HTML5 Canvas?

If you need to work on different layers on HTML5 canvas what is the best way of doing it? I see some people decide to stack a number of canvases ontop of one another using position: absolute. Is this the best way?

like image 511
Andrew Junior Howard Avatar asked May 25 '12 09:05

Andrew Junior Howard


Video Answer


1 Answers

Personally, I wouldn't stack canvas' on top of each other. A canvas is really just a bitmap displaying all the pixels you need so you should only need one for most cases.

I would suggest using a library to help you manage different objects. I have found that Grant Skinner's EaselJS is a breeze to work with.

This library lets you easily group objects and add them to the canvas, it also makes it trivial to add mouse listeners to capture clicks on objects etc. which is something that you would have to write lots of code to do when using canvas without a library.

There is documentation and examples on EaselJS also.

EDIT :

Here is an extract from the docs regarding the container used to group objects.

A Container is a nestable display lists that allows you to work with compound display elements. For example you could group arm, leg, torso and head Bitmaps together into a Person Container, and transform them as a group, while still being able to move the individual parts relative to each other. Children of containers have their transform and alpha properties concatenated with their parent Container. For example, a Shape with x=100 and alpha=0.5, placed in a Container with x=50 and alpha=0.7 will be rendered to the canvas at x=150 and alpha=0.35. Containers have some overhead, so you generally shouldn't create a Container to hold a single child.

like image 135
Neil Avatar answered Oct 18 '22 10:10

Neil