Drawing Rectangles
You'll learn how to draw, outline, and erase rectangular shapes on a canvas using three essential methods.
Now that you have your 2D rendering context, it's time to put pixels on screen. The canvas provides three fundamental rectangle methods that work like a digital painter's toolkit for rectangular shapes.
The Three Rectangle Methods
fillRect() - Solid Filled Rectangles
fillRect(x, y, width, height) draws a solid rectangle filled with the current fill color. Think of it like stamping a colored rectangle onto your canvas.
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'blue';
ctx.fillRect(50, 50, 150, 100); // x, y, width, height
strokeRect() - Outlined Rectangles
strokeRect(x, y, width, height) draws just the outline of a rectangle using the current stroke style. It's like using a pencil to draw a border without filling it in.
ctx.strokeStyle = 'red';
ctx.lineWidth = 3;
ctx.strokeRect(250, 50, 150, 100);
clearRect() - Erasing Rectangles
clearRect(x, y, width, height) erases a rectangular area, making it fully transparent. This is your digital eraser—perfect for creating cutouts or clearing sections for redrawing.
ctx.clearRect(100, 100, 50, 50); // Cuts a hole in our blue rectangle
Combining Methods
These methods work together beautifully. You might fill a rectangle, then clear a portion to create a frame effect, or layer multiple stroked and filled rectangles to build complex visualizations like bar charts.
The coordinate system starts at the top-left corner (0,0), with x increasing rightward and y increasing downward.
Key Takeaway: The three rectangle methods—fillRect() for solid shapes, strokeRect() for outlines, and clearRect() for erasing—are your fundamental building blocks for drawing and manipulating rectangular content on the canvas.