- Canvas code sample
- Canvas code sample discussion
- Body code
- Script code
- Related topics
This code sample covers the following tasks that demonstrate the basic principles of using Canvas to draw these game elements:
- Adding a Canvas element to a webpage
- Creating a black background
- Drawing random stars on the background
- Adding a spaceship to the background
At the end of the code sample is discussion material that explains more about the design and structure of these tasks and how they work.
Canvas code sample
Canvas code sample discussion
This section explains the design and structure of the code sample. It tells you about the different parts and how they fit together. The Canvas sample uses a standard HTML5 header, <!doctype html>, so that browsers can distinguish it as part of the HTML5 specification.
This code is divided into two major parts:
- Body Code
- Script Code
The body tag uses the onload function to call the canvasSpaceGame function when the page is loaded. The canvas tag is part of the body. The initial width and height of the Canvas is specified, as is the ID attribute. The ID is required so that the canvas element can be added to the object model of the page.
The script code includes three functions: canvasSpaceGame, stars, and makeShip. The canvasSpaceGame function is called when the page is loaded. The stars and makeShip are called from canvasSpaceGame.
This function is called on page load. It gets the canvas by using the ID of the canvas element in the body code. It then gets the context of the canvas, making it ready to accept drawing. After the context is initialized as a 2D canvas, the canvas is painted black by using the fillStyle property, and the rect and fill methods.
This function is called from canvasSpaceGame. It uses a for loop to generated 50 potential star positions on an x,y surface, and fillStyle is used to create a white color. Then a check is made to see if the x,y coordinates are too close to the upper-left corner. If a star might be drawn too close to the upper-left corner, the fillStyle is changed to black so it does not interfere with the space ship. Then each star is drawn with the arc method and the appropriate fill color is used.
The ship was created by drawing two ovals, one on top of the other. It was first drawn in Adobe Illustrator CS5, and the image was exported to Canvas by using the Ai2Canvas plug-in from
http://visitmix.com/labs/ai2canvas/. The resulting Canvas code was copied and pasted into the code for this sample.