Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to make a game in JavaScript

Making your own game can be an exciting and rewarding experience. In this post, we will learn how to create a simple game using JavaScript, HTML, and CSS. This tutorial is designed for someone who is learning programming, so we'll do our best to avoid jargons and explain any terms that might be unfamiliar. We'll provide actual code examples and use intuitions and analogies to help you understand the concepts.

Setting up the game canvas

The first step in creating a game is to set up a canvas, which is essentially a blank area on which we can draw and animate our game. We will use HTML to create the canvas and then manipulate it using JavaScript. Here's the basic HTML structure to create a canvas:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>My Game</title>
  <style>
    canvas {
      border: 1px solid black;
    }
  </style>
</head>
<body>
  <canvas id="gameCanvas" width="480" height="320"></canvas>
  <script src="game.js"></script>
</body>
</html>

In this code snippet, we create a canvas element with an ID of gameCanvas and a specified width and height. We also add some CSS to give it a border. The game.js script will contain our game logic.

Initializing the game

Next, let's create the game.js file and initialize our game. We'll start by selecting the canvas element, getting its 2D context (the drawing surface), and setting up some basic variables for our game:

const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");

let xPos = 240;
let yPos = 160;
let xSpeed = 2;
let ySpeed = 2;

In this code, we use document.getElementById() to select the canvas element we created earlier. We then get its 2D context using getContext("2d"), which allows us to draw on the canvas. The xPos and yPos variables will store the current position of our game object, and the xSpeed and ySpeed variables will store the speed at which the object moves in the x and y directions.

Drawing the game object

Now that our canvas is set up and our game variables are initialized, we need to draw the game object. For simplicity, we'll use a rectangle. We'll create a function called draw() that will clear the canvas and draw the rectangle at its current position:

function draw() {
  // Clear the canvas
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // Draw the rectangle
  ctx.fillStyle = "red";
  ctx.fillRect(xPos, yPos, 20, 20);

  // Request the browser to call draw() again for the next frame
  requestAnimationFrame(draw);
}

// Call the draw() function to start the game loop
draw();

In this code, we use the clearRect() method to clear the canvas, and then the fillRect() method to draw the rectangle. We set the color of the rectangle using the fillStyle property. The requestAnimationFrame() function tells the browser to call our draw() function again when it's time to update the next frame of the animation. This creates a loop that continuously updates the canvas, giving us smooth animation.

Moving the game object

Now that our game object is drawn on the canvas, let's make it move. We'll update the object's position based on its speed and use the requestAnimationFrame() function to continuously update the canvas:

function update() {
  // Update the object's position
  xPos += xSpeed;
  yPos += ySpeed;

  // If the object hits the canvas edge, reverse its direction
  if (xPos + 20 > canvas.width || xPos < 0) {
    xSpeed = -xSpeed;
  }
  if (yPos + 20 > canvas.height || yPos < 0) {
    ySpeed = -ySpeed;
  }

  // Call the draw() function to update the canvas
  draw();
}

// Call the update() function to start the game loop
update();

In this code, we create an update() function that modifies the xPos and yPos variables based on the xSpeed and ySpeed values. We also check if the object has hit the edge of the canvas, and if so, we reverse its direction by negating its speed. Finally, we call the draw() function to update the canvas and use requestAnimationFrame() to create a smooth animation loop.

Putting it all together

Now that we've covered the basics of creating a simple game in JavaScript, let's put all the code together:

<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>My Game</title>
  <style>
    canvas {
      border: 1px solid black;
    }
  </style>
</head>
<body>
  <canvas id="gameCanvas" width="480" height="320"></canvas>
  <script src="game.js"></script>
</body>
</html>
// game.js
const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");

let xPos = 240;
let yPos = 160;
let xSpeed = 2;
let ySpeed = 2;

function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  ctx.fillStyle = "red";
  ctx.fillRect(xPos, yPos, 20, 20);

  requestAnimationFrame(update);
}

function update() {
  xPos += xSpeed;
  yPos += ySpeed;

  if (xPos + 20 > canvas.width || xPos < 0) {
    xSpeed = -xSpeed;
  }
  if (yPos + 20 > canvas.height || yPos < 0) {
    ySpeed = -ySpeed;
  }

  draw();
}

update();

With this code, you now have a simple game where a red rectangle moves around the canvas and bounces off its edges. This is just the beginning, and you can expand on this foundation to create more complex games by adding user input, more game objects, and game logic.

In this tutorial, we've covered the basics of game development in JavaScript by creating a simple game with a moving object. We learned how to set up a canvas, initialize game variables, draw game objects, and update their positions to create smooth animations. With this foundation, you can start building more complex games and experimenting with different game mechanics. Happy coding!