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

Mitya picture Mitya · Aug 28, 2012 · Viewed 7.3k times · Source

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?

Answer

noncom picture noncom · Aug 29, 2012

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:

  1. Apply certain transformations to a whole layer.
  2. 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.
  3. Isolate anything that happens in a layer from happening in other layers.
  4. Disable/enable whole layers.
  5. 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!