Game Development Reference
In-Depth Information
// anyone needing to worry about the width
and height of thecanvas
this.clear = function() {
ctx.clearRect(0, 0, width, height);
};
};
We also hide some of the detailed functionality of the canvas API by adding a few
helper functions, such as getWidth , getHeight , and clear , so that other areas
in the code can interact with the canvas through this simplified interface.
One other reason that an abstraction such as this can be very handy is that it would
greatly simplify things if we decided to use two or more canvases. Suppose we
wanted to render a widget into its own canvas. Without an abstraction like this, we
would now have four separate variables to keep track of in our code.
A common optimization pattern in HTML5 game rendering with the 2D canvas is to
separate the rendering into layers. For example, things that don't change very fre-
quently from frame to frame (such as the background graphics of a level) can be re-
rendered much less frequently than dynamic objects that may need to be rendered at
a different location each frame (the player and the enemies that are trying to kill the
hero). Instead of redrawing each and every pixel of the background graphics each
frame, since most of those pixels are the exactly same as the previous frame, we
can draw the entire background scene onto its own canvas and absolutely position it
behind another canvas that only draws on smaller parts of it, making it much easier
to redraw every frame.
Since the background layer doesn't change too often, if at all, we can render more
complex graphics onto it and not have to worry about redrawing anything there very
often. Although the foreground layer normally needs to be cleared and redrawn every
single frame, we can still maintain a good frame rate because we're normally only
rendering on a small portion of the foreground canvas, which doesn't take as much
processing as it would to redraw the background layer every frame.
Search WWH ::




Custom Search