CodeBlanks Logo Icon CodeBlanks

Scene and player

JavaScript course · Expert · Lesson 49/63

Set up a scene and player drawing on a canvas 2D context.

The player rectangle

We keep scene objects as JavaScript objects. The player object has four properties: x and y for the top-left corner, width and height for its size.

For example { x: 180, y: 120, width: 40, height: 40 } places a 40x40 square at point (180, 120). The canvas origin is the top-left corner; the y axis grows downward.

The draw loop

Each frame we first clear the scene with ctx.clearRect(0, 0, canvas.width, canvas.height). Then we draw the player with ctx.fillRect(player.x, player.y, player.width, player.height). Finally we request the next frame with requestAnimationFrame(draw).

These three steps live in a draw function, and the loop starts with a draw() call. Clear → draw → request again.

Exercise Draw the scene and player

Define player as { x: 180, y: 120, width: 40, height: 40 }. Then add a draw function: clear the scene with ctx.clearRect, set the color to "#2563eb" with ctx.fillStyle, draw the player with ctx.fillRect and keep the loop running with requestAnimationFrame(draw). Finally start it with draw().

Show example solution
const player = { x: 180, y: 120, width: 40, height: 40 };

function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = "#2563eb";
  ctx.fillRect(player.x, player.y, player.width, player.height);
  requestAnimationFrame(draw);
}

draw();

Test yourself

  1. Set a color with fillStyle

    ctx.fillStyle = ____;
    Show answer
    ctx.fillStyle = "#2563eb";
  2. Which method fills a rectangle with color?

    • strokeRect()
    • clearRect()
    • fillRect()
    • drawRect()
    Show answer

    fillRect() — Correct! fillRect(x, y, w, h) fills the inside with color.

  3. Match the canvas methods

    clearRect
    Clear area
    fillRect
    Paint rectangle
    fillStyle
    Set color
    getContext
    Get context

All lessons in Expert