CodeBlanks Logo Icon CodeBlanks

Project: Canvas mini game

JavaScript course · Expert · Lesson 48/63

Overview of the 5-lesson canvas mini-game project: scene, motion, collision and game loop.

Project: Canvas mini game

In this 5-lesson project we'll build a canvas mini game. The player moves a blue square with the arrow keys; touching the green target scores a point and moves the target to a new spot.

The structure we'll build step by step:

  • canvas and 2D drawing context
  • Scene and player drawing
  • Keyboard motion
  • Collision detection
  • Score and game loop

Each lesson continues on top of the previous one's solution.

Game architecture

The mini game has three core parts: state (player and target positions), input (keyboard keys) and the draw loop. Each frame the loop first clears the scene, then draws the objects, finally processes input to update positions.

This loop runs at about 60 frames per second with requestAnimationFrame. Each frame is so fast that the player sees smooth motion.

Exercise Set up the canvas and 2D context

The page already has a <canvas id="gameCanvas"> element. Select it with document.querySelector("#gameCanvas") and assign it to a canvas variable. Then get the 2D drawing context with canvas.getContext("2d") and assign it to a ctx variable.

Show example solution
const canvas = document.querySelector("#gameCanvas");
const ctx = canvas.getContext("2d");

Test yourself

  1. Which method returns the 2D drawing context of a canvas element?

    • getContext("2d")
    • getCanvas("2d")
    • fillRect("2d")
    • drawImage("2d")
    Show answer

    getContext("2d") — Correct! getContext("2d") returns the 2D drawing context.

  2. Select the canvas element

    const canvas = document.____;
    Show answer
    const canvas = document.querySelector("#gameCanvas");
  3. Match the game terms

    Canvas
    2D drawing surface
    Context
    Drawing context
    requestAnimationFrame
    Frame loop
    fillRect
    Fill rectangle

All lessons in Expert