I’ve been tinkering with the html5 canvas element for a while now. It is very useful and all, but I feel very, very limited by the fact that I apparently cannot organize the canvas with objects (not natively).
For instance, if I draw a rectangle, or any other shape, I would really find it useful to be able to access its different properties somewhere else in the script. Instead of that, it seems they just remain, well, drawings, and you have to manually keep track of what is on the canvas, and clear it and rewrite it again when you want to change anything.
My question is: am I missing something ? Is JavaScript providing us with ways to handle objects inside the canvas? If not, are there libraries that do just that already? Which one would you say is the best?
Canvas aren’t really any different from any other drawing-tools. You really do have to keep track of what you’re drawing. The trick is how you do it. It’s a pretty good idea to use objects for it and it’s not that hard. You just need to pass along the
contextof the canvas to any object, for it to interact with the canvas and draw on it. So if you have an object called Foo you can make the object decide how it wants to be drawn. For instance it could have a method like so:In your main drawing loop you could have code similar to this:
This would allow you to create objects with their own methods of drawing. There are several ways to do it of course, but the advantage of this one is that it’s pretty modular. If you want you can have several types of objects that inherit from the same generic type with some nifty tools and so on…
Hope that helps!
P.S.: I just remembered a brilliant tutorial on the whole HTML 5/canvas stuff: It’s on MDN here.