Drawing Rectangles and Paths
Use fillRect, strokeRect, and path commands to draw shapes.
Canvas Setup
The <canvas> element requires explicit width and height attributes for pixel dimensions. Get the 2D context: const ctx = canvas.getContext("2d"). All drawing operations use this context object.
<canvas id="c" width="800" height="600"></canvas>
const ctx = document.getElementById("c").getContext("2d");fillRect and strokeRect
Draw rectangles without paths: ctx.fillRect(x, y, width, height) fills a solid rectangle. ctx.strokeRect(x, y, width, height) draws the outline. Set ctx.fillStyle and ctx.strokeStyle before drawing.
ctx.fillStyle = "#3b82f6";
ctx.fillRect(50, 50, 200, 100);
ctx.strokeStyle = "#1e3a8a";
ctx.lineWidth = 3;
ctx.strokeRect(50, 50, 200, 100);All lessons in this course
- Setting Up the Canvas and 2D Context
- Drawing Rectangles and Paths
- Text and Images on Canvas
- Animation with requestAnimationFrame