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 nextctx.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:
- A green field: a rectangle across the bottom (from y = 140 down to 200)
- 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.