An example of creating a space game using HTML5 canvas


HTML5 canvas can quickly create lightweight images that are helpful for game development. This section explains how to use canvas to create a nostalgic style outer space flight game that will run on the web page. This game is designed to show the basic principles of developing web games using canvas function. The goal of this space game is to make your spacecraft pass through the star field with exploding asteroids and return to the base safely.
This tutorial contains the complete code to run the game. The code is written using HTML5 canvas and JavaScript and contains four independent annotated code examples. Each example involves a key programming task that is necessary to develop different aspects of the game. The fourth code example combines all tasks together to create a complete and effective game. You can use the arrow keys to move the spacecraft through the star maze distributed with exploding red asteroids. If your ship hits a planet, it will be destroyed. In order to return to the base safely, you must avoid the asteroid or blow it up before you hit it. The score will be based on the number of times you move the ship and the number of bombs you launch.
This topic includes a separate annotated code example that shows you how to use HTML5 canvas and JavaScript to create random areas containing white stars and draw orange and green spaceships shaped like Frisbees. This game image was created in pixels. By using instant mode, canvas has the ability to put pixels directly on the screen. This feature allows you to easily draw points, lines, and shapes in the colors you choose where you need them. This code example will show you how to create a spaceship by combining mathematical Bezier curves and colors in a shape. It will then show you how to draw stars using a small circle of arcs.
This code example contains the following tasks to demonstrate the basic principles of drawing these game elements using canvas:
1. Add canvas element to web page
2. Create a black background
3. Draw random stars on the background
4. Add spacecraft to the background
At the end of the code example are discussion materials that illustrate details about the design and structure of these tasks and how they work.
Canvas code example:

Copy code

The code is as follows:

<!DOCTYPE html>
<script type=”text/javascript”>
// This function is called on page load.
function canvasSpaceGame() {
// Get the canvas element.
canvas = document.getElementById(“myCanvas”);
// Make sure you got it.
if (canvas.getContext)
// If you have it, create a canvas user inteface element.
// Specify 2d canvas type.
ctx = canvas.getContext(“2d”);</p>
<p>// Paint it black.
ctx.fillStyle = “black”;
ctx.rect(0, 0, 300, 300);
<p>// Paint the starfield.
<p>// Draw space ship.
<p>// Paint a random starfield.</p>
function stars() {</p>
<p>// Draw 50 stars.
for (i = 0; i <= 50; i++) {
// Get random positions for stars.
var x = Math.floor(Math.random() * 299)
var y = Math.floor(Math.random() * 299)</p>
<p>// Make the stars white
ctx.fillStyle = “white”;</p>
<p>// Give the ship some room.
if (x < 30 || y < 30) ctx.fillStyle = “black”;</p>
<p>// Draw an individual star.
ctx.arc(x, y, 3, 0, Math.PI * 2, true);
<p>function makeShip() {</p>
<p>// Draw saucer bottom.
ctx.moveTo(28.4, 16.9);
ctx.bezierCurveTo(28.4, 19.7, 22.9, 22.0, 16.0, 22.0);
ctx.bezierCurveTo(9.1, 22.0, 3.6, 19.7, 3.6, 16.9);
ctx.bezierCurveTo(3.6, 14.1, 9.1, 11.8, 16.0, 11.8);
ctx.bezierCurveTo(22.9, 11.8, 28.4, 14.1, 28.4, 16.9);
ctx.fillStyle = “rgb(222, 103, 0)”;
<p>// Draw saucer top.
ctx.moveTo(22.3, 12.0);
ctx.bezierCurveTo(22.3, 13.3, 19.4, 14.3, 15.9, 14.3);
ctx.bezierCurveTo(12.4, 14.3, 9.6, 13.3, 9.6, 12.0);
ctx.bezierCurveTo(9.6, 10.8, 12.4, 9.7, 15.9, 9.7);
ctx.bezierCurveTo(19.4, 9.7, 22.3, 10.8, 22.3, 12.0);
ctx.fillStyle = “rgb(51, 190, 0)”;
<body onload=”canvasSpaceGame()”>
Canvas Space Game
<canvas width=”300″ height=”300″>

Canvas code example discussion

This section describes the design and structure of this code example. It shows you the different parts of the code and how to integrate them. The canvas example uses a standard HTML5 header so that browsers can distinguish it as part of the HTML5 specification.

The code is divided into two main parts:
1. Subject code
2. Script code

Subject code
When the page is loaded, the body tag uses the onload function to call the canvasspacegame function. The canvas tag is part of the body. Specifies the initial width and height of the canvas, as well as the ID attribute. You must use an ID to add a canvas element to the object model of the page.

Script code
The script code includes three functions: Canvas spacegame, stars and makeship. The canvasspacegame function is called when the page is loaded. Both stars and makeship are called from canvas spacegame.

Canvasspacegame function
This function is called when the page is loaded. It gets the canvas by using the canvas element ID in the body code, then gets the context of the canvas and is ready to accept the drawing. After initializing the context as a 2D canvas, use the fillStyle, rect, and fill methods to paint the canvas black.

Stars function
This function is called from canvasspacegame. It uses for loop to generate 50 potential star positions on a two-dimensional plane, and then uses fillStyle to create white. Then, a check will be made to confirm whether the X and Y coordinates are too close to the upper left corner. If the stars are drawn too close to the upper left corner, the fillStyle is changed to black so that it does not interfere with the spacecraft. Then, use the arc method to draw each star and use the corresponding fill color.
This function is called from canvasspacegame. Draw a simple spaceship using a series of beginpath, moveto, bezierCurveTo, closepath, fillStyle, and fill methods.
The spaceship is created by drawing two ellipses, one on top of the other. It first draws in Adobe Illustrator CS5, and then exports the image to canvas using the ai2canvas plug-in. The generated canvas code has been copied and pasted into the code for this example.