How to use HTML 5 canvas to create a space game

Source: Internet
Author: User
Tags object model

HTML5 Canvas can quickly create lightweight images that help with game development. This section explains how to use Canvas to create a retro-style outer space flight game that will run in a Web page. This game is designed primarily to demonstrate the basic principles of developing WEB games using the Canvas feature. The goal of this space game is to make your spaceship safely return to the base, through the Star field that distributes the exploding asteroid.

This tutorial contains the complete code to run the game. The code is written using HTML5 Canvas and JavaScript, and contains four separate annotated code examples. Each example involves a critical programming task that is required to develop different aspects of the game. The fourth code example combines all the tasks together to create a complete and effective game where you can use the arrow keys to move the spacecraft through the maze of stars that are scattered over the exploding red asteroid. If your ship crashes into a planet, it will be destroyed. To safely return to the base, you must avoid the asteroid or blow it up before you hit an asteroid. will be based on your number of mobile spacecraft and the number of bombs you fired to score.

This topic includes a separate annotated code example that shows you how to create a random area of white stars with HTML5 Canvas and JavaScript, and to draw an orange-green spaceship shaped like a frisbee. This game image is created using pixels. By using instant mode, Canvas has the ability to place pixels directly on the screen. This feature allows you to easily draw dots, lines, and shapes in the desired location in the selected color. This code example shows you how to create a spaceship by combining mathematical Bezier curves and colors in a shape. It then shows how to draw the stars using small circles composed of arcs.

This code example includes the following tasks to demonstrate the basic principles of drawing these game elements using canvas:

1. Add a Canvas element to a Web page

2. Create a black background

3. Draw random stars on the background

4. Add spacecraft to the background

The end of the code example is a discussion material that describes the design and structure of these tasks and the details of how they work.

Canvas code Example:

<! DOCTYPE html>


<html>





<head>


<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");





//Paint it black.


Ctx.fillstyle = "BLACK";


ctx.rect (0, 0, 300, 300);


Ctx.fill ();





//Paint the Starfield.


stars ();





//Draw space ship.


Makeship ();


        }


      }





//Paint a random starfield.








function Stars () {





//Draw stars.


for (i = 0; I <= i++) {


//Get random positions for the stars.


var x = Math.floor (Math.random () * 299)


var y = Math.floor (Math.random () * 299)





//Make the white


Ctx.fillstyle = "white";





//Give the ship some room.


if (x < | | | y <) Ctx.fillstyle = "BLACK";





//Draw an individual star.


Ctx.beginpath ();


Ctx.arc (x, y, 3, 0, Math.PI * 2, true);


Ctx.closepath ();


Ctx.fill ();


        }


      }





function Makeship () {





//Draw saucer bottom.


Ctx.beginpath ();


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.closepath ();


Ctx.fillstyle = "RGB (222, 103, 0)";


Ctx.fill ();





//Draw saucer top.


Ctx.beginpath ();


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.closepath ();


Ctx.fillstyle = "rgb (51, 190, 0)";


Ctx.fill ();


      }


</script>


</head>


  


<body onload= "Canvasspacegame ()" >


<h1>


Canvas Space Game


</h1>


<canvas id= "MyCanvas" width= "height=" >


</canvas>


</body>





</html>





Canvas code Sample discussion

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

The code is divided into two main sections:

1. Main code

2. Script code

Body Code

When the page loads, the principal 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, and also specifies the ID attribute. You must use an ID to add the canvas element to the page's object model.

Scripting code

The scripting code includes three functions: Canvasspacegame, stars, and Makeship. The Canvasspacegame function is called when the page is loaded. Both stars and Makeship are called from the Canvasspacegame.

Canvasspacegame function

This function is called when the page is loaded. It obtains the canvas by using the Canvas element ID in the principal code, and then gets the context of the canvas and is ready to accept the drawing. After the context is initialized to a 2D canvas, the canvas is drawn to black using the FillStyle, Rect, and fill methods.

Stars function

This function is called from the Canvasspacegame. It uses a For loop to generate 50 potential star locations on a two-dimensional plane, and then uses FillStyle to create white. A check is then made to confirm that the x,y coordinates are too close to the upper left corner. If the star is drawn too close to the upper-left corner, the FillStyle will be changed to black so that it does not interfere with the spaceship. Then, use the Arc method to draw each star and use the appropriate fill color.

Makeship

This function is called from the Canvasspacegame. A simple spaceship is drawn using a series of Beginpath, MoveTo, Beziercurveto, Closepath, FillStyle, and fill methods.

The spacecraft is created by drawing two ellipses, one ellipse on top of the other. It first draws in Adobe Illustrator CS5, and then uses the Ai2canvas plug-in to export the image to Canvas. The generated Canvas code has been copied and pasted into the code for this example.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.