Share via


Drawing the background and vehicle for a game using HTML5 canvas and JavaScript

This topic explains how to use HTML5 canvas and JavaScript to draw a star field background and a flying vehicle for a game you create.

  • Canvas code sample
  • Canvas code sample discussion
    • Body code
    • Script code
  • Related topics

This topic includes a stand-alone annotated code sample that shows you how to use HTML5 Canvas and JavaScript to create a random field of white stars and draw a green and orange spaceship that looks like a flying saucer. This game imagery is created using pixels. Canvas has the ability to put pixels directly on the screen by using immediate mode. This feature makes it easy to draw points, lines, and shapes exactly where you want them to go and in whatever color you choose. This code sample will show you how to create the spaceship by combining mathematical bezier curves and coloring in the shape. Then it explains how to draw stars by using small circles made out of arcs.

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

<!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 interface 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 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)

          // Make the stars white
          ctx.fillStyle = "white";

          // Give the ship some room.
          if (x < 30 || y < 30) 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="300" height="300">
    </canvas>
  </body>

</html>

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

Body 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.

Script code

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.

canvasSpaceGame function

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.

stars function

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.

makeShip

This function is called from canvasSpaceGame. Using a series of beginPath, moveTo, bezierCurveTo, closePath, fillStyle, and fill methods, a simple space ship is drawn.

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 https://visitmix.com/labs/ai2canvas/. The resulting Canvas code was copied and pasted into the code for this sample.

How to Use Canvas to Create a Space Game