Chapter 1. Graphics Foundations: Canvas and Sprites
HTML5’s canvas element makes it
much easier to create complex graphic games, offering far more flexibility
and speed than older approaches that relied on moving images around with
the Document Object Model (DOM). Canvas lets you draw on an area of the
screen directly with JavaScript, letting you apply traditional game
graphics approaches in a web
context. Though it’s a recent addition to the HTML universe, canvas is widely supported
on newer desktop and mobile browsers.
Working with the canvas Object
The canvas element allows us to
define an extremely fast drawable region on the screen that can be
controlled using JavaScript with pixel-level accuracy. However, canvas works in immediate
mode. Unlike Scalable Vector Graphics (SVG, not covered in
this book), the calls that we make to the HTML5
Canvas API draw the graphics directly in the canvas, without
holding any reference to them once they are displayed. If we want to
move our graphics 10 pixels to the right, we need to clear the display
and redraw them using the new coordinates. Later on, we discuss a
technique called “adaptive tile refresh” that avoids having to clear the
whole display just to modify a small part of the canvas.
You can look at the canvas object as if it were a piece of paper; you have many crayons (among other tools) that you can use to draw things on it. So if, for example, you want to draw a red line, grab the red crayon and draw the line. If you want to draw ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access