In this tutorial, we'll walk through building a simple JavaScript game using the HTML5 element. The game involves controlling a red square (the player) using the left and right arrow keys to avoid falling blue squares. Let's get started!

Step 1: Setting Up the HTML Structure

Create an index.html file and add the following boilerplate code:

</span>
 lang="en">
  
     charset="UTF-8" />
     name="viewport" content="width=device-width, initial-scale=1.0" />
    Simple Canvas Game
  
  
     width="900" height="600">
    <span class="na">src="script.js">
  




    Enter fullscreen mode
    


    Exit fullscreen mode
    




This sets up an empty canvas element and links a script.js file where we'll write our game logic.
  
  
  Step 2: Initializing the Canvas and Variables
Create a script.js file and add the following code to set up the canvas and game variables:

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

let rightPressed = false;
let leftPressed = false;
let playerX = canvas.width / 2;
const playerSize = 50;
const squares = [];
let score = 0;



    Enter fullscreen mode
    


    Exit fullscreen mode
    





  
  
  Step 3: Handling Player Input
Add event listeners to detect when arrow keys are pressed:

document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);

function keyDownHandler(e) {
  if (e.key === "Right" || e.key === "ArrowRight") {
    rightPressed = true;
  } else if (e.key === "Left" || e.key === "ArrowLeft") {
    leftPressed = true;
  }
}

function keyUpHandler(e) {
  if (e.key === "Right" || e.key === "ArrowRight") {
    rightPressed = false;
  } else if (e.key === "Left" || e.key === "ArrowLeft") {
    leftPressed = false;
  }
}



    Enter fullscreen mode
    


    Exit fullscreen mode
    





  
  
  Step 4: Creating Falling Squares
We generate obstacles (falling squares) and update their positions:

for (let i = 0; i < 5; i++) {
  squares.push({
    x: Math.random() * (canvas.width - playerSize),
    y: Math.random() * -canvas.height,
    size: playerSize,
  });
}



    Enter fullscreen mode
    


    Exit fullscreen mode
    





  
  
  Step 5: Drawing Game Elements
Define functions to draw the player, falling squares, and the score:

function drawPlayer() {
  ctx.beginPath();
  ctx.rect(playerX, canvas.height - playerSize - 5, playerSize, playerSize);
  ctx.fillStyle = "red";
  ctx.fill();
  ctx.closePath();
}

function drawSquares() {
  squares.forEach((square) => {
    ctx.beginPath();
    ctx.rect(square.x, square.y, square.size, square.size);
    ctx.fillStyle = "blue";
    ctx.fill();
    ctx.closePath();

    square.y += 3;
    if (square.y > canvas.height) {
      square.y = 0 - square.size;
      square.x = Math.random() * (canvas.width - playerSize);
    }

    if (
      playerX < square.x + square.size &&
      playerX + playerSize > square.x &&
      canvas.height - playerSize - 5 < square.y + square.size
    ) {
      alert("Game Over! Your score: " + score);
      document.location.reload();
    }
  });
}



    Enter fullscreen mode
    


    Exit fullscreen mode
    





  
  
  Step 6: Updating the Game Loop
The game loop continuously updates and renders the game state:

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

  ctx.beginPath();
  ctx.strokeRect(0, 0, canvas.width, canvas.height);
  ctx.closePath();

  drawPlayer();
  drawSquares();
  drawScore();

  if (rightPressed) {
    playerX = Math.min(playerX + 7, canvas.width - playerSize);
  } else if (leftPressed) {
    playerX = Math.max(playerX - 7, 0);
  }

  requestAnimationFrame(draw);
}

draw();



    Enter fullscreen mode
    


    Exit fullscreen mode
    





  
  
  Step 7: Scoring System
Add a simple score counter that updates every second:

function drawScore() {
  ctx.font = "16px Arial";
  ctx.fillStyle = "black";
  ctx.fillText("Score: " + score, 8, 20);
}

setInterval(() => {
  score++;
}, 1000);



    Enter fullscreen mode
    


    Exit fullscreen mode
    





  
  
  Conclusion
You've now built a simple JavaScript game using the HTML5 Canvas API! This game can be expanded with additional features such as different difficulty levels, sound effects, and animations.