Learn Canvas and JavaScript Animation by Creating a Vertical Shooter (INTRODUCTION) – Part 1

In the 1980’s vertical shooters became popular and one of the most popular was 1942 by Capcom. I wasted many hours playing the Commodore 64 version so when a few years ago a college of mine showed me a simple GameMaker tutorial on how to create a 1942 clone I was excited.

This project is inspired by 1942 using the same sprites[1] from that old YoYo GameMaker tutorial. To see a similar clone created in Scratch 2.0[2] using the same game sprites, click here. If you would like to see the Scratch algorithm click the “See inside” button.


Above: To try the finished game click on the image
 

Additional Content
For those doing the NSW HSC or IB Diploma some of the content contained in these orange panels cover mandatory outcomes. Otherwise the content is just interesting or explains a concept linked to the immediate context.

<Canvas> Coordinate System

This tutorial will introduce you to the HTML5 <canvas> element, JavaScript mouse coordinates, audio and native JavaScript drawing functions. The HTML Canvas allows the drawing of computer graphics and shapes like lines and paths and has some built in functions to help with programming games and animations.

Before the <canvas> tag web browsers needed to use plugins like Adobe Flash to do complex drawing operations. Today all modern browsers can display the <canvas> element.

Coordinates for a HTML Canvas are the same as your normal mathematics classes Cartesian Coordinate system (x,y) except that the values are all referenced from the top left of the screen as shown below:

 Above: Click for more detail

 

Planning the solution

The graphics and sound for this game are very simple. We need a couple of enemy planes, the main player’s ship and some islands. Online you can find what are called “sprite sheets”. These are sometimes freely downloadable and able to be used in non-commercial projects. Try searching “sprite sheets” in google for some examples.

This tutorial will us the YoYo GameMaker sprites and game sounds, but feel free to replace these with anything you like. The download link is here.

 

Sprite Sheets
The image drawing method that we use has the ability to create a sprite from part of an image. This makes it easy to use sprite sheets without having to “cut” the image manually into separate files. This method can also help with the loading performance of your game. See the w3schools website for information on how to use a section of an image and convert it to its own sprite: link

It is helpful to break projects, particularly when you are starting out, into small achievable chunks. We will therefore build our code in stages with each step building upon the last. See the diagram below for how we will initially break up the first 5 steps. As you can see there will be other steps after this but let’s start with these.

Above: Click for more detail

 

Stage 1: Initialisation and setup

I’ll be creating this using the Netbeans IDE so all of the screenshots will relate to that but any IDE will do. I won’t be setting out the steps for how to create a folder using NetBeans or how to click “New File” etc.

Stage 1 involves creating a NetBeans project, setting up the <canvas> and loading any images we need. The preliminary steps to do this are:

  • Create a new HTML5/JavaScript project called “1945”.
  • Create three folders; css, js, images, sound.
  • Create a new JavaScript file called “1945.js” in the js folder
  • Create a new CSS file called “1945.css” in the css folder
  • Download the images and sounds from the link  here  and save them into the images and sound folders. Your project folder will look like the structure on the right.

Our HTML and CSS code is very straight forward. The HTML will create a <canvas> on the page and the CSS will colour it blue.

The code for each looks like:

 

File 1: index.html

<html>
    <head>
        <title>Vertical Shooter</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link href="css/1945.css" rel="stylesheet" type="text/css"/>
        <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20src%3D%22js%2F1945.js%22%20type%3D%22text%2Fjavascript%22%3E%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;script&gt;" title="&lt;script&gt;" />
    </head>
    <body>
       <center>
        <canvas id="gameCanvas" tabindex="1"></canvas>
       </center>
    </body>
</html>

 

File 2: 1945.css

Our CSS file is even simpler with only one style that changes the background colour of our <canvas> element from white to blue and the page colour to black:

#gameCanvas{
   background-color: #0141AD;
}
html, body {
    background-color: #000000; 
    overflow: hidden;
}

If you run our game now you should just see a small blue square. From now on we can ignore the HTML and CSS files as all the game code will be written in our JavaScript file.

HTML Colour representation

HTML Colours are commonly represented using their Red, Green and Blue intensity value. For a 24-bit colour system; 8 bits are dedicated to Red intensity, 8 bits to Green intensity and 8 bits to Blue intensity. In HTML these 8 bit values can be represented as either a decimal value from 0-255, a 2 digit Hexadecimal value or by their colour name (for some colours).Example colours and their equivalent HTML code:

  • Black ( Red, Green Blue ): background-color: black;
    • Decimal: (0,0,0): background-color: rgb(0,0,0);
    • Hexadecimal: (00,00,00): background-color: #000000;
  • White ( Red, Green Blue ): background-color: white;
    • Decimal: (255,255,255): background-color: rgb(255,255,255);
    • Hexadecimal: (FF,FF,FF): background-color: #FFFFFF;
  • Red ( Red, Green Blue ): background-color: red;
    • Decimal: (255,0,0): background-color: rgb(255,0,0);
    • Hexadecimal: (FF,0,0): background-color: #FF0000;
  • Cyan ( Red, Green Blue ): background-color: cyan;
    • Decimal: (0,255,255): background-color: rgb(0,255,255);
    • Hexadecimal: (0,FF,FF): background-color: #00FFFF;

As part of our final setup we need to resize our <canvas> and load the images. Open the 1945.js file and start our JavaScript with the following code:

File 3: 1945.js

var gameCanvas;
var ctx;
var canvasWidth = 900;
var canvasHeight = 800;

window.onload = function () {
    	gameCanvas = document.getElementById("gameCanvas");
    	gameCanvas.width = canvasWidth; 
    	gameCanvas.height = canvasHeight; 
    	ctx = gameCanvas.getContext("2d");
};

 

Description of JavaScript code

The global variables at the start of our code will store some of the values we need for our game. Remember that it is best to try to minimise global variables because it makes code reuse easier and reduces the possibility of variable clashes.

We will add more global variables later but at present the only three we need will store the width and height of our canvas and the canvas drawing context (see below).

Drawing Context

To draw on our canvas we need to tell JavaScript that we will be using the built-in API[3] functions for a 2D coordinate space.To do that we need to get the canvas’ 2d context, this is done with the line:

gameCanvas.getContext(“2d”);

Rather than writing the following every time we want to draw and image:

gameCanvas.getContext(“2d”).drawImage();

We will save the context into a global variable called “ctx” so we can just write: ctx.drawImage() or ctx.clearRect() or ctx.fillText().

The line of code starting with window.onload is a built-in event in JavaScript that is run once when the webpage has finished loading. It runs after all linked scripts, images and css files have been loaded. Without this, JavaScript code might run before the resources they need are loaded, resulting in unpredictability.

Currently our window.onload function does four things. These are, in order:

  1. Create a variable storing our <canvas> element. This line looks for any HTML element with the ID of “gameCanvas” and stores it in a variable called gameCanvas. We use this in the next lines to set the width and height of the <canvas>.
  2. Sets the <canvas> width to 900 pixels.
  3. Sets the <canvas> height to 800 pixels.
  4. Gets the <canvas> drawing context. We will use this later to do all our graphics drawing functions. See the note on Drawing Context for more information

Run your code, the only thing you should see is that our blue box is now 900px wide and 800px high. If this is too big for your screen change the values of canvasWidth and canvasHeight.

Move on to stage 2 –>
Jump to: [Vertical Shooter Post: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 ]

 


[1] A sprite in computer games is a two-dimensional bitmap image.

[2]https://scratch.mit.edu/ is a visual programming language for learning coding and problem solving. Well worth playing with to get an introductory understanding of basic control structures and the logic programming.

[3] API stands for Application Programming Interface. API’s provide a way to access a system or library. In the case of our drawing context the API is our way to access complex graphics drawing functions. A programmer need only know what a function does and how to run them, with the detailed coding is hidden (abstracted) inside the API library.