Question

How to Clear an HTML Canvas for Redrawing in JavaScript

htmljavascriptcanvashtml5-canvascomposite

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:

  1. Clearing pixels removes what is currently visible.
  2. Resetting canvas state is different. Settings like globalCompositeOperation, transform, fillStyle, or globalAlpha may 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:

  1. Erase the board
  2. Draw the current scene again

That is the standard redraw cycle used in animations and games.

Take Quiz

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:

  1. const canvas = document.getElementById('myCanvas');

    • JavaScript gets the <canvas> element from the page.
  2. const ctx = canvas.getContext('2d');

    • This creates the 2D drawing context used for all canvas drawing operations.
  3. ctx.fillStyle = 'orange';

    • The fill color is set to orange.
  4. ctx.fillRect(10, 10, 80, 80);

    • An orange square is drawn.
    • The pixels now exist on the canvas.
  5. ctx.clearRect(0, 0, canvas.width, canvas.height);

    • Everything inside the full canvas area is erased.
    • The orange square disappears.
  6. ctx.fillStyle = 'purple';

    • The fill color changes to purple.
  7. 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.

Take Quiz

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

ApproachWhat it doesKeeps transparency?Resets drawing state?Typical use
ctx.clearRect(0, 0, canvas.width, canvas.height)Clears pixels in the given areaYesNoStandard redraw loop
ctx.fillRect(0, 0, canvas.width, canvas.height) with a background colorPaints over old contentNo, unless using transparency manuallyNoWhen you want a solid background
canvas.width = canvas.widthClears the canvas and resets context stateYesYesFull 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.width only when you intentionally want a complete reset of both content and state.
Take Quiz

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:
    1. clear
    2. update state
    3. 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.

Take Quiz

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.
Take Quiz

Keep learning

Related questions

View more