Chapter 39: Canvas Rectangles

1. What are “Canvas Rectangles” actually?

Canvas Rectangles means using JavaScript on the <canvas> element to draw rectangular shapes — normal rectangles, squares, rounded rectangles, filled rectangles, bordered rectangles, transparent rectangles, gradient rectangles, shadowed rectangles, and so on.

Rectangles are the easiest and most frequently used shape in Canvas because:

  • They form backgrounds
  • They make buttons, cards, panels, borders
  • They are used for cropping images
  • They create charts (bar charts = filled rectangles)
  • They act as bounding boxes, hit areas, overlays

There are three main methods to draw rectangles:

  1. fillRect(x, y, width, height) → filled (solid color / gradient / pattern)
  2. strokeRect(x, y, width, height) → only border / outline
  3. rect(x, y, width, height) + fill() / stroke() → more flexible (can combine with other path commands)
  4. roundRect(x, y, width, height, radius) → modern rounded corners (supported in all browsers 2025+)

2. Your First Canvas Rectangle – Hello World Style (Copy-Paste & Run)

Create canvas-rectangle-hello.html:

HTML

What you see:

  • 4 different rectangles side by side
  • Solid filled blue
  • Red border only
  • Green filled + border
  • Purple rounded corners

3. All Important Rectangle Commands (With Copy-Paste Snippets)

A. fillRect() – Filled rectangle (most common)

JavaScript

B. strokeRect() – Border only

JavaScript

C. roundRect() – Rounded corners (modern & beautiful)

JavaScript

D. rect() + fill() / stroke() – More flexible (can combine with other paths)

JavaScript

E. Clear rectangle (erase / cut hole)

JavaScript

4. Teacher’s Quick Tips (Hyderabad Student Style 😄)

  • fillRect() & strokeRect() are fastest — use them when you only need rectangles
  • roundRect() is modern (Chrome/Edge/Firefox/Safari 2024+) — fallback to arc() for older browsers if needed
  • Always set fillStyle / strokeStylebefore drawing — they don’t apply retroactively
  • Common mistake #1: Draw rectangle but forget fill() or stroke() → invisible!
  • Common mistake #2: Use CSS border on canvas → it’s outside the drawing surface (won’t be part of exported image)
  • Pro tip: Use ctx.save() / ctx.restore() when changing styles
JavaScript

Understood Canvas Rectangles fully now? Rectangles are the easiest shape and appear in almost every canvas project — master them and you’re ready for cards, buttons, charts, overlays, cropping, everything.

Tell me what you want next — we can build on this:

  • Full modern card with gradient + rounded + shadow?
  • Bar chart using only rectangles?
  • Rounded rectangle button with hover effect?
  • Animated growing/shrinking rectangle?
  • Or 15-question Canvas rectangles quiz?

Just say — we keep going step by step together! 🚀

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *