SyntaxStudy
Sign Up
HTML Drawing Rectangles on Canvas
HTML Beginner 4 min read

Drawing Rectangles on Canvas

Canvas Rectangles

Canvas provides three rectangle methods: fillRect() draws a filled rectangle, strokeRect() draws an outlined rectangle, and clearRect() erases an area.

Example
const ctx = canvas.getContext("2d");

// Filled rectangle
ctx.fillStyle = "#007bff";
ctx.fillRect(20, 20, 150, 80);

// Outlined rectangle
ctx.strokeStyle = "#dc3545";
ctx.lineWidth = 3;
ctx.strokeRect(200, 20, 150, 80);

// Clear a region
ctx.clearRect(50, 40, 50, 40);

// All take: x, y, width, height
Pro Tip

Use clearRect(0, 0, canvas.width, canvas.height) at the start of each animation frame to wipe the canvas clean.