Back to: GAMES
- Setup the canvas
- Setup game loop
- Draw the ship
- Move ship left
- Move ship right
- Thrust the ship
- Shoot laser
- Draw asteroids
- Destroy asteroids
- Detect collisions
- Detect boundaries
- Keep score
- Game over
The first job is to set up the canvas.
<canvas id="gameCanvas" width="1280" height="720"></canvas>
//canvas setup
let canvas = document.getElementById("gameCanvas");
let context = canvas.getContext("2d");
variables and constants
The game contains values that will be used frequently. The best way to deal with these is by using variables and constants. Variables are for items that will change and constants are for items that will stay the same throughout the game. Therefore I will begin writing the JavaScript by defining some variables and constants. I will need to know the canvas width, canvas height, what key has been pressed, number of lives,
let canvas;
let ctx;
let canvasWidth = 1400;
let canvasHeight = 1000;
let keys = [];
let ship;
let bullets = [];
let asteroids = [];
let score = 0;
let lives = 3;
detecting page load
It would be a nice feature to only be able to start the game when the page has loaded. This can be achieved by adding an event handler. An event handler allows you to monitor an event and trigger an action when it occurs. In this instance I will achieve this by:
document.addEventListner('DOMContentLoaded', SetupCanvas);
Let’s break this down.
The first part, document, is called the target. This is the HTML element that you wish to add your event handler to.
Then the addEventListner() is a method that allows us to act on the HTML element. addEventListner() accepts three parameters, the third is optional. The first is the event that we want to monitor. We can use an event called DOMContentLoaded to detect when the page has loaded and can then trigger the start of the game. The second parameter is what you want to run, in this case SetupCanvas.