Question
How to Clear an HTML Canvas for Redrawing in JavaScript
Question
After experimenting with composite operations and drawing images on a canvas, I now want to remove the existing drawings and compositing effects. How can I do that?
I need to clear the canvas so I can redraw other images repeatedly. This may happen many times, so I want an efficient approach rather than drawing a new rectangle over the canvas each time.
Short Answer
By the end of this page, you will understand how to clear an HTML canvas before drawing again, when to use clearRect(), how canvas state behaves during redraws, and which clearing patterns are commonly used in real JavaScript applications such as games, animations, and image editors.
Concept
The main concept behind this question is clearing an HTML <canvas> before redrawing.
A canvas does not automatically forget what was drawn before. Once you draw a shape, image, or effect, the pixels stay there until you explicitly change or clear them. This is why old drawings remain visible when you try to render something new.
The most common way to clear a canvas is:
ctx.clearRect(0, 0, canvas.width, canvas.height);
This removes the pixels in the specified rectangle, usually the entire canvas.
Why this matters:
- Animations need to erase the previous frame before drawing the next one.
- Games redraw moving objects many times per second.
- Image editors need to replace previews and overlays.
- Interactive tools often redraw after mouse movement or user input.
There are two related ideas to understand:
- Clearing pixels removes what is currently visible.
- Resetting canvas state is different. Settings like
globalCompositeOperation,transform,fillStyle, orglobalAlphamay still remain unless you reset them yourself.
So, clearing the canvas removes the image content, but not necessarily all drawing settings.
Mental Model
Think of the canvas like a whiteboard.
- Drawing on the canvas is like using a marker on the board.
clearRect()is like using an eraser on part or all of the board.- Drawing a filled rectangle over everything is like painting over the board instead of erasing it.
If you are repeatedly updating what the user sees, the normal process is:
- Erase the board
- Draw the current scene again
That is the standard redraw cycle used in animations and games.
Syntax and Examples
The basic syntax for clearing a canvas is:
ctx.clearRect(x, y, width, height);
To clear the entire canvas:
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
Example: draw, clear, redraw
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// Draw a red square
ctx.fillStyle = 'red';
ctx.fillRect(20, 20, 100, 100);
// Clear the whole canvas
ctx.clearRect(0, 0, canvas.width, canvas.);
ctx. = ;
ctx.(, , , );
Step by Step Execution
Consider this example:
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'orange';
ctx.fillRect(10, 10, 80, 80);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'purple';
ctx.fillRect(30, 30, 80, 80);
Step by step:
-
const canvas = document.getElementById('myCanvas');- JavaScript gets the
<canvas>element from the page.
- JavaScript gets the
-
const ctx = canvas.getContext('2d');- This creates the 2D drawing context used for all canvas drawing operations.
-
ctx.fillStyle = 'orange';
Real World Use Cases
Here are common situations where canvas clearing is necessary:
Animations
A moving object is redrawn every frame:
- clear previous frame
- draw object at new position
Games
Games often redraw the entire scene many times per second:
- player movement
- enemies
- background effects
- score overlays
Image preview tools
If a user uploads a new image or changes crop settings, the canvas is cleared and the latest preview is drawn.
Drawing applications
When showing temporary guides, selections, or brush previews, the canvas may be cleared and redrawn based on current state.
Data visualizations
Charts built on canvas often clear the previous render before drawing updated data.
Real Codebase Usage
In real projects, developers usually do not just "draw and forget." They follow a redraw pattern.
Common redraw pattern
function render() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBackground();
drawSprites();
drawUI();
}
This works well because the current visual state is recreated from data each time.
Resetting state before drawing
If your code changes settings such as composition, transforms, or alpha, you may need to reset them:
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.globalAlpha = 1;
ctx.globalCompositeOperation = 'source-over';
ctx.clearRect(0, 0, canvas.width, canvas.height);
This is useful if older drawing state should not affect the next frame.
Resizing as a reset
Another pattern is:
Common Mistakes
1. Forgetting to clear before redrawing
Broken example:
function animate() {
ctx.fillRect(x, 40, 50, 50);
x += 2;
requestAnimationFrame(animate);
}
Problem:
- Every frame adds another square
- old frames remain visible
Fix:
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(x, 40, 50, 50);
x += 2;
requestAnimationFrame(animate);
}
2. Clearing the wrong area
Broken example:
ctx.clearRect(0, 0, 100, 100);
Problem:
Comparisons
| Approach | What it does | Keeps transparency? | Resets drawing state? | Typical use |
|---|---|---|---|---|
ctx.clearRect(0, 0, canvas.width, canvas.height) | Clears pixels in the given area | Yes | No | Standard redraw loop |
ctx.fillRect(0, 0, canvas.width, canvas.height) with a background color | Paints over old content | No, unless using transparency manually | No | When you want a solid background |
canvas.width = canvas.width | Clears the canvas and resets context state | Yes | Yes | Full reset |
clearRect() vs drawing a rectangle
- Use when you want to erase existing pixels.
Cheat Sheet
// Clear the whole canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Clear part of the canvas
ctx.clearRect(x, y, width, height);
// Reset everything by resizing
canvas.width = canvas.width;
Quick rules
- Canvas drawings stay visible until you overwrite or clear them.
clearRect()removes pixels from a rectangular area.- To clear everything, use the full canvas size.
clearRect()does not fully reset styles, transforms, alpha, or composition settings.- Drawing a rectangle over the canvas is not the same as clearing it.
- For animation, the usual order is:
- clear
- update state
- draw again
Useful reset values
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.globalAlpha = 1;
ctx.globalCompositeOperation = 'source-over';
Common full redraw pattern
FAQ
How do I clear an HTML canvas in JavaScript?
Use:
ctx.clearRect(0, 0, canvas.width, canvas.height);
This clears the entire drawing area.
Is clearRect() better than drawing a white rectangle?
Usually, yes. clearRect() actually removes the pixels, while a white rectangle just paints over them.
Does clearRect() reset globalCompositeOperation or other canvas settings?
No. It clears pixels, but most drawing state remains unchanged.
How do I completely reset a canvas?
You can reset the canvas by assigning its width again:
canvas.width = canvas.width;
This clears the pixels and resets the drawing context state.
Should I clear the canvas on every animation frame?
In most animations, yes. That prevents old frames from remaining visible.
Can I clear only part of the canvas?
Yes. Pass the rectangle you want to erase:
ctx.(, , , );
Mini Project
Description
Build a simple canvas demo where a square moves across the screen. The project demonstrates why clearing the canvas is necessary before each redraw. Without clearing, the square leaves a trail. With proper clearing, the animation looks smooth and correct.
Goal
Create a canvas animation that clears the previous frame and redraws a moving square in its new position.
Requirements
- Create an HTML canvas element and get its 2D context.
- Draw a square that moves horizontally across the canvas.
- Clear the entire canvas before drawing each new frame.
- Reset the square to the left side when it moves off the canvas.
- Use
requestAnimationFrame()for the animation loop.
Keep learning
Related questions
Allow Only Numeric Input (0-9) in HTML Input Using jQuery
Learn how to allow only digits 0-9 in an HTML input using jQuery, with examples, validation tips, common mistakes, and best practices.
CSS :not() Selector for Excluding a Class or Attribute
Learn how to use the CSS :not() selector to target elements that do not have a specific class or attribute, with examples and common mistakes.
Can HTML Checkboxes Be Readonly? Understanding readonly vs disabled in HTML Forms
Learn why HTML checkboxes do not support readonly, how disabled differs, and practical ways to prevent changes while still submitting values.