Tutorial: How to make a top-down shooter in JavaScript

Lesson 1) Creating a game area with canvas

Every good battle needs an arena

In this tutorial I won't explain basic stuff like what an if statement is and what a for loop does (see Codecademy and the like for that). I'm focusing on how to fit those pieces together to make a game. That said, I'm assuming you're a beginner, so if you've got some skills, you'll be skimming through some sections. If you get stuck, remember that at any point you can use Ctrl+U to see the actual code used for each lesson.

The structure of the game - looping the canvas

A Canvas is a HTML element which, as the name imlies, let's you draw graphics on it. We make games with it by drawing our game elements (e.g., the player, bad guys, and bullets) on the canvas, and then creating a loop in which the positions of these elements are updated, and then re-drawn in their new places. It'll work something like this:
  1. Clear the canvas.
  2. Check if the player has moved or fired. If so, update the player position and create the bullets.
  3. Do the same with the bad guys.
  4. Update the positions of the bullets.
  5. Check if there are any collisions between the player, bad guys, and bullets. If so, resolve these by reducing the player's health, removing bad guys, removing bullets, etc, as needed.
  6. Re-draw the canvas and all elements
  7. Go to (1)
The drawing and clearing happens quicker than the eye can detect, giving the illusion of smooth movement.

Drawing the canvas

Our JavaScript code will sit inside a HTML file and run in a browser, so first we need to set up the HTML file. Just put the following into a text document and save it with a .html extention:
<!DOCTYPE html>

canvas {
border: solid 1px black;

#holder {
margin: 20px auto 0 auto;




<div id = "holder">
<canvas id="canvas" width="800" height="600" tabindex='1'></canvas>


What this does

The CSS for the page is in the <style> tags at the top. We've made an element called "canvas" and given it a black border, and a div called "holder," which is just a little container for the canvas.

Under that we've got the <script> tags - the JavaScript code will go in here.

In the <body> area, we've used our holder div, and put within it a canvas with the highly inventive name "canvas."

The end result is shown below. Pretty spartan for a game area. We'll start filling it with fun stuff in the next lesson.

Go to Lesson 2 - Drawing on the canvas