Canvas Draw Rectangles

What You’ll Learn
Rectangles are one of the fastest shapes to draw on canvas. You can draw them as filled shapes, outlined shapes, or even erase areas using rectangles.
This page covers fillRect(), strokeRect(), and clearRect() with a hands-on live preview.
⚡ Quick Reference
// filled rectangle
ctx.fillRect(x, y, width, height);
// outlined rectangle
ctx.strokeRect(x, y, width, height);
// clear (erase) rectangle area
ctx.clearRect(x, y, width, height);x, yTop-left corner
width, heightMust be > 0 to show
fillStyleColor/gradient/pattern
strokeStyle + lineWidthOutline + thickness
👀 Live Preview — Fill, Stroke, Clear
Use the controls to draw a filled rectangle, add an outline, or clear (erase) a region. This preview draws a background grid so clearing is obvious.
Note: clearRect() clears pixels to transparent. If your canvas sits on a colored background, that background will show through.
Filled + Stroked Rectangle
This mirrors the legacy example but uses clean modern style defaults.
<canvas id="myCanvas" width="240" height="200"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// Filled rectangle
ctx.fillStyle = 'blue';
ctx.fillRect(50, 50, 120, 80);
// Stroked rectangle
ctx.strokeStyle = 'black';
ctx.lineWidth = 3;
ctx.strokeRect(30, 30, 170, 130);
</script>Erase a Region with clearRect()
A common pattern in games/animations is: draw background → draw objects → clear a region (or clear the whole canvas) before the next frame.
// Draw something
ctx.fillStyle = '#2563eb';
ctx.fillRect(40, 40, 180, 120);
// Erase a rectangular region (transparent pixels)
ctx.clearRect(90, 70, 60, 50);💡 Best Practices
Do
- Use
fillRect()for fast solid blocks and backgrounds - Set
lineWidthbeforestrokeRect()when you need an outline - Use
clearRect()to erase areas (transparent pixels) - Keep rectangle math in variables for readability and reuse
- Consider devicePixelRatio scaling for crisp rendering on HiDPI screens
Don’t
- Assume rectangles automatically clear previous drawings (they paint over pixels)
- Use negative width/height without knowing the effect you want
- Forget that
strokeRect()draws centered on the rectangle edge (half the stroke goes outside) - Overuse clearRect in complex scenes without profiling
- Ignore alpha/composite settings that may affect fill/stroke
❓ Frequently Asked Questions
fillRect() paints a solid rectangle. strokeRect() draws an outline using stroke styles.fillRect()/strokeRect()/clearRect(). Those draw immediately. Use paths if you need ctx.rect() + fill()/stroke().Next: Linear Gradients
Make rectangles look modern by filling them with smooth gradients.
4 people found this page helpful
