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.height);
// Draw a blue square
ctx.fillStyle = 'blue';
ctx.fillRect(50, 50, 100, 100);
Example: clear before each animation frame
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
let x = 0;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'green';
ctx.fillRect(x, 40, 50, 50);
x += 2;
requestAnimationFrame(animate);
}
animate();
In this example:
clearRect()removes the previous frame- the square is drawn at a new position
- the loop repeats smoothly
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';- The fill color is set to orange.
-
ctx.fillRect(10, 10, 80, 80);- An orange square is drawn.
- The pixels now exist on the canvas.
-
ctx.clearRect(0, 0, canvas.width, canvas.height);- Everything inside the full canvas area is erased.
- The orange square disappears.
-
ctx.fillStyle = 'purple';- The fill color changes to purple.
-
ctx.fillRect(30, 30, 80, 80);- A new purple square is drawn on the now-cleared canvas.
Important detail:
- The canvas pixels were cleared.
- The drawing context still exists.
- Any settings you changed earlier may still remain unless you change them again.
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:
canvas.width = canvas.width;
This clears the canvas and resets the drawing state. It can be useful, but developers usually use it only when they really want a full reset, not just a visual clear.
Offscreen rendering
More advanced codebases may draw onto an offscreen canvas, clear that canvas, and then copy the result to the visible one. This helps organize rendering and improve responsiveness in some cases.
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:
- Only part of the canvas is erased
- old drawings may remain outside that region
Fix:
ctx.clearRect(0, 0, canvas.width, canvas.height);
3. Assuming clearRect resets all settings
Broken assumption:
ctx.globalCompositeOperation = 'multiply';
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Developer expects composition mode to be normal again
Problem:
clearRect()clears pixels, but does not fully reset context settings
Fix:
ctx.globalCompositeOperation = 'source-over';
4. Painting over the canvas instead of truly clearing it
Example:
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, canvas.width, canvas.height);
This is not always wrong, but it is different:
- it draws white pixels
- it does not create transparency
- it depends on the current fill style and compositing behavior
Use clearRect() when you want actual clearing.
5. Forgetting transforms affect drawing and clearing logic
If the context has been translated, rotated, or scaled, your draw behavior may not match your expectations. In complex cases, reset the transform before clearing and redrawing.
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, canvas.width, canvas.height);
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
clearRect()when you want to erase existing pixels. - Use
fillRect()when you want to replace the background with a visible color.
clearRect() vs resetting canvas width
- Use
clearRect()for normal frame-by-frame redraws. - Use
canvas.width = canvas.widthonly when you intentionally want a complete reset of both content and state.
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
function render() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawScene();
}
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.clearRect(10, 10, 100, 50);
Why do my old images still appear after drawing a new one?
Because canvas is immediate-mode drawing. New drawing does not automatically remove previous content unless you clear or overwrite it.
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
Add a Favicon to a Static HTML Page
Learn how to add a favicon to static HTML pages, use correct paths and icon formats, and troubleshoot browser caching and local-file issues.
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.
Apply CSS !important with jQuery .css()
Learn why jQuery .css() cannot set !important and how to use CSSStyleDeclaration.setProperty() to apply inline important styles safely.