Code / JavaScript from Zero / Unit 6: Canvas and your first game

Drawing on a canvas कैनवस पर चित्र

Lesson 13 of 15 · about 12 minutes · fillStyle, fillRect and arc.

⚡ 0 XP

Step 1 of 1

Rectangles and circles

x →y ↓fillRectarc

A <canvas> is a drawing board. Get its 2D context — your paintbrush — with canvas.getContext("2d").

  • Coordinates start at the top-left corner: x grows to the right, y grows down
  • ctx.fillStyle = "green"; picks the colour for what you draw next
  • ctx.fillRect(x, y, width, height) paints a rectangle
  • A circle: ctx.beginPath(); ctx.arc(x, y, radius, 0, Math.PI * 2); ctx.fill();

Things drawn later appear on top, like layers of paint.

Example
const ctx = document.querySelector("canvas").getContext("2d");
ctx.fillStyle = "#FF9933";
ctx.fillRect(0, 0, 300, 40);
ctx.fillStyle = "white";
ctx.fillRect(0, 40, 300, 40);
ctx.fillStyle = "#138808";
ctx.fillRect(0, 80, 300, 40);
ctx.fillStyle = "navy";
ctx.beginPath();
ctx.arc(150, 60, 15, 0, Math.PI * 2);
ctx.fill();

A simple tricolour with a navy circle

🎯 Challenge: Sunrise over the fields +20 XP

The sky is already painted. Add:

  1. A green field: a rectangle across the bottom (from y = 140 down to 200)
  2. An orange sun: a circle in the top half of the canvas (y less than 100), filled with fill()

Use a different fillStyle for each part.

Try twice to unlock the solution (0/2)

script.jsCtrl ⏎
Preview
Console

Output from console.log appears here.

Checklist

Press Run to check your code.

  • A field rectangle is drawn near the bottom
  • A sun circle is drawn in the top half and filled
  • At least three different colours are used
Lesson notes (text version)

1. Rectangles and circles

A <canvas> is a drawing board. Get its 2D context — your paintbrush — with canvas.getContext("2d").

  • Coordinates start at the top-left corner: x grows to the right, y grows down
  • ctx.fillStyle = "green"; picks the colour for what you draw next
  • ctx.fillRect(x, y, width, height) paints a rectangle
  • A circle: ctx.beginPath(); ctx.arc(x, y, radius, 0, Math.PI * 2); ctx.fill();

Things drawn later appear on top, like layers of paint.

                const ctx = document.querySelector("canvas").getContext("2d");
ctx.fillStyle = "#FF9933";
ctx.fillRect(0, 0, 300, 40);
ctx.fillStyle = "white";
ctx.fillRect(0, 40, 300, 40);
ctx.fillStyle = "#138808";
ctx.fillRect(0, 80, 300, 40);
ctx.fillStyle = "navy";
ctx.beginPath();
ctx.arc(150, 60, 15, 0, Math.PI * 2);
ctx.fill();
              

Challenge: Sunrise over the fields

The sky is already painted. Add:

  1. A green field: a rectangle across the bottom (from y = 140 down to 200)
  2. An orange sun: a circle in the top half of the canvas (y less than 100), filled with fill()

Use a different fillStyle for each part.

Search by task, format or tool name.