Skip to content
Lesson 1 of 9 Free Preview
Duration: 20 min

The Canvas

Learn it

<canvas> is a drawing surface. Get its 2D context and draw rectangles, circles and text. (0, 0) is the top-left; y grows downwards.

🧰 Tool: a free online editor such as CodePen or JSFiddle, or a plain text editor and your web browser.

Code examples

HTML

<canvas id="game" width="480" height="320"></canvas>
JavaScript

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

ctx.fillStyle = "#0f172a";
ctx.fillRect(0, 0, canvas.width, canvas.height);

ctx.fillStyle = "#22c55e";
ctx.fillRect(40, 240, 60, 40);

ctx.beginPath();
ctx.arc(240, 120, 30, 0, Math.PI * 2);
ctx.fillStyle = "#facc15";
ctx.fill();

ctx.fillStyle = "white";
ctx.font = "20px sans-serif";
ctx.fillText("Score: 0", 10, 25);

Project: Draw a scene

  1. Draw ground, a sun and a player box.
  2. Add text.
  3. Draw 10 stars with a loop and Math.random().

Challenge: Draw a house with triangles using moveTo/lineTo.

Enjoying this lesson?

Enroll in the full course to access all lessons, track your progress, and earn a certificate.

Enroll in Full Course