Canvas Rectangles
Canvas provides three rectangle methods: fillRect() draws a filled rectangle, strokeRect() draws an outlined rectangle, and clearRect() erases an area.
Canvas provides three rectangle methods: fillRect() draws a filled rectangle, strokeRect() draws an outlined rectangle, and clearRect() erases an area.
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
Use clearRect(0, 0, canvas.width, canvas.height) at the start of each animation frame to wipe the canvas clean.