On an <canvas>, rectangles are the quickest shapes to draw. Use fillRect() for a solid box, strokeRect() for an outline, and clearRect() to erase a region.
Those three methods paint immediately and do not change the current path. Prefer rect() or roundRect() when you want the rectangle as part of a larger path before fill() / stroke().
Baseline · Widely available.
fillRect, strokeRect, clearRect, and rect are stable since about July 2015. roundRect is Baseline widely available since about April 2023.
Immediate vs path.
fillRect / strokeRect draw now. rect / roundRect only add geometry — you still call fill() or stroke().
Syntax
Syntax
rect.js
ctx.fillRect(x, y, width, height);
ctx.strokeRect(x, y, width, height);
ctx.clearRect(x, y, width, height);
ctx.beginPath();
ctx.rect(x, y, width, height);
ctx.fill(); // or stroke()
(x, y) is the top-left corner for positive sizes. Positive width goes right; positive height goes down.
Add the rounded box to the path with a radius (here 20).
Fill and stroke like any other path.
Radii can also be an array, similar to CSS border-radius.
Edge Cases & Pitfalls
Most rectangle bugs come from mixing immediate draws with path draws, or forgetting to clear between frames.
immediate
fillRect skips the path
A later stroke() will not outline that box. Use strokeRect, or rect + stroke.
clear
clearRect is transparent, not white
If the page background shows through, that is expected. Fill a background color if you need opaque white.
size
Negative width/height flip the box
The covered area uses absolute size, but the starting corner effectively flips. Prefer positive sizes for clarity.
crisp
1px strokes can look blurry
For sharp 1px borders, try half-pixel coords (e.g. x + 0.5) so the stroke sits on a pixel boundary.
round
roundRect is newer
Widely available since about April 2023. Feature-detect, or fall back to quadratic corners as on the quadratic page.
Compatibility
Browser Support
fillRect, strokeRect, clearRect, and rect are core Canvas 2D. roundRect needs a modern browser.
✓ Baseline · Widely available
Rectangles
Core rectangle methods: widely available since about July 2015. roundRect: Baseline widely available since about April 2023 across Chrome, Firefox, Safari, and Edge.
98%Core rect support (approx.)
Google ChromeAll modern (+ roundRect)
Full support
Mozilla FirefoxAll modern (+ roundRect)
Full support
Apple SafariAll modern (+ roundRect)
Full support
Microsoft EdgeAll modern (+ roundRect)
Full support
OperaAll modern
Full support
Samsung InternetAll modern
Full support
Internet Explorer9+ core / no roundRect
Partial
fillRect / strokeRectWidely supported
Bottom line: Use fillRect/strokeRect/clearRect everywhere. Treat roundRect as a progressive enhancement with a fallback.