Chapter 40: Canvas clearRect()

1. What is clearRect() actually? (Clear definition first)

clearRect(x, y, width, height) is the eraser / white-out / reset tool of the Canvas.

It removes / clears / wipes out everything that was previously drawn inside the rectangular area you specify.

Think of it like this:

  • You drew a circle, some text, a rectangle, some lines…
  • Now you want to erase part (or all) of the canvas to redraw something new
  • Instead of undoing every step (which is impossible in Canvas), you use clearRect() to blank out a rectangle-shaped region

Very important rule everyone must remember from day one:

  • clearRect() does not change the canvas background color — it makes the area transparent (you see whatever is behind the canvas, usually white page or whatever CSS background you set)
  • If you want a solid color background after clearing, you must redraw the background right after clearRect()

2. Syntax of clearRect() (Very Simple)

JavaScript
  • x → starting left position (from left edge of canvas)
  • y → starting top position (from top edge of canvas)
  • width → how wide the cleared area is
  • height → how tall the cleared area is

Clear the entire canvas (most common use):

JavaScript

Clear only a small part:

JavaScript

3. Your First clearRect() Example – Erase & Redraw (Copy-Paste & Run)

Create canvas-clearrect-demo.html:

HTML

What happens when you click buttons:

  • “Erase Center Area” → wipes out a rectangle in the middle (you see the page background or canvas background color)
  • “Redraw Everything” → brings back the full scene

4. Very Common Real-World Uses of clearRect()

A. Animation loop (clear before each frame)

JavaScript

B. Erase only part (like a moving eraser)

JavaScript

C. Create transparent window / cutout

JavaScript

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

  • clearRect() makes the area transparent — if you want a solid color background after clearing, redraw the background immediately after
  • Always clear before drawing new frame in animation — otherwise old drawings stay and you get trails
  • Common mistake #1: Forget to clear → old shapes keep appearing (messy animation)
  • Common mistake #2: Clear too much → accidentally erase something important
  • Pro tip: Use ctx.save() / ctx.restore() if you’re doing complex clipping + clearing
JavaScript

Understood Canvas clearRect() fully now? This is one of the most important commands in Canvas — without it, animations become messy, drawings overlap forever, and you can’t “erase” anything.

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

  • Full animated bouncing ball with clearRect()?
  • Mouse eraser / paint app (clear on drag)?
  • Loading bar that clears & redraws?
  • Canvas with transparent cutouts?
  • Or 15-question clearRect() 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 *