How to Use the Canvas Tag in Your HTML5 Game
The simpleGame engine’s Scene object uses one of the most exciting new features of HTML5 — the canvas tag. This exciting tag allows you to draw images and other elements directly on a portion of the browser.
A brief look at a game canvas
Here is a basic page displaying a canvas with two rectangles and an image.
Basic canvas drawing for your game
The canvas tag is an HTML tag, but it’s mainly used as a placeholder in HTML. The canvas tag has a context attribute, which allows the programmer to draw graphics directly on the page. Here’s how this example works:
Add a canvas tag to the HTML.
Normally, you’ll create a canvas tag in the HTML, but the simpleGame library automatically adds a canvas tag and appends it to the end of the page body.
Create a function for drawing.
In this example, the canvas is drawn in a function called when the page initially loads. In simpleGame, the drawing function will be called 20 times per second.
Get a drawing context.
The canvas tag supports a 2D drawing context (yes, 3D is coming, but it’s not yet widely supported). Use the getContext() method to make a reference to the drawing context.
Set the image’s source attribute.
To link a file to the Image object, set the src property of the Image object to an image file in the same directory as your program. This will associate an image with your document, but the image will not be drawn on the page; instead, it’s stored in memory to be used in code.
Set the fill style.
You can draw filled and open drawings with the canvas tag. The fillStyle can be set to colors as well as patterns and gradients.
You can draw an open rectangle with the strokeRect() method and a solid rectangle with the fillRect() method. In the simpleGame library, the Scene object’s clear() method simply draws a filled rectangle in the scene’s background color.
Draw the image in the canvas.
Use the drawImage() method to draw an image inside a canvas. There are many variations of this method, but the one used in simpleGame specifies the image’s position and size.