Javascript Game Foundations - Rendering

Ten Essential Foundations of Javascript Game Development

Rendering

It’s hard to imagine a video game with no visuals. It might be an interesting challenge to create
an audio-only game, but in most games we’re going to need to draw stuff, and for browser based
javascript games we are going to draw on an HTML5 <canvas> element.

Performance

On most modern desktop browsers, the <canvas> element is hardware accelerated by the GPU,
making the performance more than adequate for simple games. We can render hundreds, possibly
thousands of sprite images onto a canvas and still hit 60fps.

However, benchmarks are typically skewed and misleading. We should always measure the performance
of our actual game running under real-world conditions. Start with a simple embedded FPSMeter
so that we can keep an eye on performance during development. Once we identify a problem with a
drop in the frame rate we can turn to more detailed analysis.

On Mobile browsers it’s a completely different story. The performance of mobile browsers
will vary dramatically from device to device. It can be a very complicated battle to make our game
perform well on mobile devices. We should choose our target audience and platform wisely. Simple
games will likely perform just fine, but more complex action-oriented games might be better off
targeting native mobile platforms instead of HTML5.

Cached Rendering

As always, the fastest rendering is that which is not performed. If we can avoid rendering, we
should avoid it. There is no need to re-render a score if it hasn’t changed, or the background if
it hasn’t moved, or entities that are idle.

We can make caching possible by rendering components to an off-screen canvas, then using a simple,
and fast, ctx.drawImage call to render that component. We need only invalidate the off-screen
canvas if the state of the component changes.

Rendering a Game

Beyond the primitives, what we render is going to be entirely dependent on our game requirements.
Is it a simple 2-d platformer? A grid-based puzzle game? A pseudo-3d racing game? Do we need
particle effects? parallax backgrounds ?

If you need a few hints to get started, you can read more details about how I’ve rendered some
simple javascript games in the past: