2D Game in JavaScript example

by danielkwood

HTML

<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Catch the monster</title>
  </head>
  <body>
    <script src="game.js"></script>
  </body>
</html>

JavaScript

/*  
  Code modified from:
  http://www.lostdecadegames.com/how-to-make-a-simple-html5-canvas-game/
  using graphics purchased from vectorstock.com
*/

// Create the canvas for the game to display in
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 512;
canvas.height = 480;
document.body.appendChild(canvas);

// Load the background image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
  // show the background image
  bgReady = true;
};
bgImage.src = "https://images.squarespace-cdn.com/content/v1/62d7afdd0711b76729174013/ed85f29b-378c-465a-bfac-b29ca5ba364d/background.png";

// Load the player image
var playerReady = false;
var playerImage = new Image();
playerImage.onload = function () {
  // show the player image
  playerReady = true;
};
playerImage.src = "https://images.squarespace-cdn.com/content/v1/62d7afdd0711b76729174013/84fdf722-5a3e-48f1-910b-6d263ae511bb/player.png";

// Load the enemy image
var enemyReady = false;
var enemyImage = new Image();
enemyImage.onload = function () {
  // show the enemy image
  enemyReady = true;
};
enemyImage.src = "https://images.squarespace-cdn.com/content/v1/62d7afdd0711b76729174013/2806254c-2f41-4733-91d6-f5abe5daad23/enemy.png?format=300w";

// Create the game objects
var player = {
  speed: 256 // movement speed of player in pixels per second
};
var enemy = {};
var enemiesCaught = 0;

// Handle keyboard controls
var keysDown = {};

// Check for keys pressed where key represents the key pressed
addEventListener("keydown", function (event) {
  keysDown[event.key] = true;
}, false);

addEventListener("keyup", function (event) {
  delete keysDown[event.key];
}, false);

// Reset the player and enemy positions when player catches an enemy
var reset = function () {
  // Reset player's position to centre of canvas
  player.x = canvas.width / 2;
  player.y = canvas.height / 2;

  // Place the enemy somewhere on the canvas randomly
  enemy.x =...