I am making a game engine using HTML5 canvas, and I have decided to write some “wrappers” for images, because that gives me a common interface for various types of animation, images, etc. What I mean is that every object just has a .picture property which provides things such as a draw() method, .phi value for rotation, an .alpha, etc. What is cool about this approach to me is that, essentially, this .picture property can be anything:
- An image (a wrapper called
Pictureactually). - An animation (a wrapper for many images with some functiones such as
next()andgetImage()). - A composition (many images and animations that get drawn on top of eachother or something else that has a draw method.)
- A state (similar to composition)
For convinience, all these wrappers (image, animation, composition, state) translate and rotate the context (you can’t successfully rotate an HTML5 canvas context without translating it to the point of rotation first). Now, that’s a lot of translations! First issue: is translating the context for every draw call expensive?
Another issue is that this design implies a lot of function calls!
Here’s how the process goes:
- The renderer iterates through a scene, and then the scene’s layers
- When it gets to a drawable (
ob.picture != undefined), it calls it’s.picture‘s draw function (every visible object inherits from a “class” called Drawable, that class actually has the position and picture properties)
Here is what happens in the best-case scenario:
- The drawable’s
.pictureproperty is a Picture object (wrapper for images) - The
.picturetranslates the context to it’s position - The
.picturerotates the context - The
.picturecallscontext.drawImage(.picture.image, etc);
This is what happens in the worst-case scenario:
- The picture property is a Composition or a State object
- The composition starts iterating through it’s elements, each of which is another Picture or Animation (or, even worse, another Composition/State)
- Calls their draw methods
- They render the actual picture/iterate through their elements and this repeats
As you see, there are a lot of draw function calls. Will this be a significant speed problem, or is calling functions inexpensive?
EDIT: This question has changed a bit. The “game” became an “engine”, and the engine’s structure is altered a slight bit. But, nothing too essential or different.
Not sure about the context translation, but I assume translations are not free.
For the function calls, it depends on the amount of objects you’re drawing. A function call has a non-zero runtime length. It is very small though.
I set up a real dumb and simple example below measuring the runtime of a bunch of nested functions: http://jsfiddle.net/luketmillar/D5sHE/
When it comes to graphics every millisecond counts. If you can avoid extra function calls, might as well.