Canvas (Kinetic.JS): multiple layers vs single layer approach

canvas, html, kineticjs, layer, shapes

Solution

Actually, layers usually give a huge advantage. However, sometimes they are not necessary. Just to give an idea - compare PhotoShop (layers) and MS Paint (no layers). If this gives you the idea then that's it!

If not: layers is an organizational concept. It lets you to deal with data in pieces. They allow:

- Apply certain transformations to a whole layer.

- Automatically categorize your objects on a per-layer basis, so that you can get all objects of a layer and work with them pretty easily.

- Isolate anything that happens in a layer from happening in other layers.

- Disable/enable whole layers.

- Much-much more!

As you see, layers, generally, allow such abstractions as encapsulation and, to some extent, polymorphism to be enforced on content organization level. Pitfall that one-layer approach brings is just that - too tight coupling - a beast from the world of permanent chaos that encapsulation and polymorphism fight for the eternity. Nuff said!

Problem

Can anyone explain why (indeed, if) it's best to abstract the major parts of a canvas game to different layers when using something like Kinetic? It of course feels like you should, and so far I have been: one layer for the background, one for the player's character, and others. Then I ran into a situation where I needed a shape of one layer to sit behind a shape on another layer - but moving the entire layer behind the other layer was not an option, so I reluctantly re-coded so the entire game sits on one layer. To my surprise, though, I can still do everything I need. I can still animate or handle events on individual shapes or groups. So in short: what advantage does explicit layering bring? What pitfalls might I face with the one-layer approach?

Original source