Game Development Reference
In-Depth Information
Canvas
Perhaps no other HTML5 feature is as powerful as the canvas API with regards to
game development for the web platform. Although we may have every other feature
currently in the specification, as well as any forthcoming feature that the browser can
possibly support, it would be nearly impossible to produce a high quality, engaging,
fun game using HTML and JavaScript. The canvas API allows us to create 2D, as
well as 3D graphics right on the browser. It also lets us manipulate the graphical data
stored in the canvas context, down to the individual pixel level.
One major difference between a canvas graphic and an SVG graphic, apart from
the fact that SVG graphics are vector-based, and canvas graphics are always raster
graphics, is that the canvas is a single HTML element, and everything drawn in it is,
for all practical purposes, non-existent to the browser. Thus, any event handling on
individual entities drawn on a canvas must be handled at the application level. There
are generic events on the canvas that we can observe and respond to, such as clicks,
move events, and keyboard events. Beyond that, we are free to do as we please.
Beyond the shape-based drawing that we can do on an HTML5 canvas, there are
three major use cases for the API. We can create 2D, sprite-based games, full-blown
3D games (using WebGL with the help of the canvas), and manipulating photographs.
The last use case mentioned: photo manipulation, is especially interesting. The API
has a very handy function that allows us to not only export the data in the canvas as
a PNG or JPG image, but it also supports various types of compression. That means,
we can draw on a canvas, load graphics on it (for example photographs), manipulate
that data at a pixel level (for example apply Photoshop-like filters to it), rotate, stretch,
scale, and otherwise, play with the data. Then, the API allows us to export that data
as a compressed file that can be saved to the file system.
For the purposes of this topic, we'll focus on the aspects of the canvas API that we
can best use for game development. Although WebGL is a very exciting aspect of the
canvas element, but we will cover a very basic introduction to it in Chapter 6 , Adding
Features to Your Game . For other capabilities available on the canvas API, we will
cover them briefly with a few examples in the following section.
Search WWH ::




Custom Search