Building Your First 2D Game with JavaScript and Canvas

Learn how to build a simple but fun 2D game using only HTML, CSS, and JavaScript Canvas. Perfect for beginners who want hands-on experience.

Game development may sound intimidating at first, but with modern web technologies, you can build interactive games with just a few lines of code. In this tutorial, we’ll create a simple 2D game where a player controls a square that must dodge falling objects.

Step 1: Setting Up the HTML Structure

Start with a simple HTML file. We need a <canvas> element where the game will be rendered.

<!DOCTYPE html>
<html>
<head>
  <title>2D Game</title>
  <style>
    canvas {
      background: #000;
      display: block;
      margin: auto;
    }
  </style>
</head>
<body>
  <canvas id="gameCanvas" width="400" height="600"></canvas>
  <script src="game.js"></script>
</body>
</html>

Step 2: Drawing on Canvas

In game.js, we grab the canvas and draw the player:

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

let player = { x: 180, y: 550, width: 40, height: 40, color: 'lime' };

function drawPlayer() {
  ctx.fillStyle = player.color;
  ctx.fillRect(player.x, player.y, player.width, player.height);
}

Step 3: Movement and Controls

We want the player to move left and right using arrow keys.

document.addEventListener('keydown', (e) => {
  if (e.key === 'ArrowLeft' && player.x > 0) player.x -= 20;
  if (e.key === 'ArrowRight' && player.x < canvas.width - player.width) player.x += 20;
});

Step 4: Adding Falling Objects

let obstacles = [];

function createObstacle() {
  obstacles.push({
    x: Math.random() * (canvas.width - 40),
    y: 0,
    width: 40,
    height: 40,
    color: 'red'
  });
}
setInterval(createObstacle, 1000);

Step 5: Game Loop and Collision

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

  obstacles.forEach(ob => {
    ob.y += 5;
    ctx.fillStyle = ob.color;
    ctx.fillRect(ob.x, ob.y, ob.width, ob.height);

    if (
      ob.x < player.x + player.width &&
      ob.x + ob.width > player.x &&
      ob.y < player.y + player.height &&
      ob.y + ob.height > player.y
    ) {
      alert('Game Over!');
      document.location.reload();
    }
  });

  requestAnimationFrame(update);
}
update();

Step 6: Adding Style and Enhancements

You can make the game more engaging by adding background music, increasing difficulty, or showing a score.

Key Takeaways:

  • JavaScript Canvas makes real-time game rendering easy.
  • Simple collision detection can create fun, interactive mechanics.
  • You can build and expand this project into more complex games.