Your Search Bar For Shrewd Tips

How Do I Clear Html Canvas?


Clearing an HTML canvas removes the pixels currently drawn on it, allowing you to redraw a scene or prepare for a new frame. For a 2D canvas, the usual method is the context’s clearRect() function. The key is to clear the full drawing area using the canvas’s internal dimensions—not just its displayed CSS size—and to account for transforms or clipping that might affect the operation.

In most cases, you can clear a canvas with one line of JavaScript:

const canvas = document.querySelector("#myCanvas");
const ctx = canvas.getContext("2d");

ctx.clearRect(0, 0, canvas.width, canvas.height);

This clears the entire canvas to transparent pixels. The examples and guidance below explain how the method works, how to clear a canvas reliably, and what to check when the canvas does not appear to clear.

How to Clear an HTML Canvas with clearRect()

The clearRect(x, y, width, height) method clears a rectangular area of a 2D canvas. Its position and dimensions are measured in the canvas’s coordinate system. To clear the whole drawing surface, start at the top-left corner, (0, 0), and use the canvas’s internal width and height:

ctx.clearRect(0, 0, canvas.width, canvas.height);

Clearing removes the existing drawing from that region, making it transparent. It does not paint the area white. If the canvas is displayed over a colored page or another element, that background may show through after you clear it.

You can also clear only part of the canvas. For example, this clears a 100-by-50-pixel rectangle beginning 20 pixels from the left and 30 pixels from the top:

ctx.clearRect(20, 30, 100, 50);

Use partial clearing when you need to erase a small region, such as part of a drawing application. For animations and games, clearing the full canvas before drawing each new frame is often simpler.

Clear the Canvas Before Drawing Again

A common canvas task is to update a drawing repeatedly. Without clearing, each new frame is drawn over the previous one, which can leave trails or make the image appear smeared. Clear the canvas at the beginning of your drawing function, then draw the current frame:

function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // Draw the current frame here.
  ctx.fillRect(50, 50, 80, 80);
}

For an animation, call the function with requestAnimationFrame(). Schedule the next frame from inside the drawing function so the browser can coordinate the animation with its display refresh:

function animate() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // Update positions and draw the scene here.

  requestAnimationFrame(animate);
}

animate();

Clear before drawing the next frame, not after it. If you clear at the end, the canvas may be blank when the browser displays that frame. In some animations, you may intentionally leave a translucent trail rather than clearing completely. That effect usually involves drawing a semi-transparent fill over the canvas, not using clearRect().

Use the Canvas’s Internal Width and Height

A canvas has two sizes that are easy to confuse: its internal drawing size and its displayed CSS size. The HTML attributes width and height set the drawing surface’s resolution. CSS controls how large the canvas appears on the page.

<canvas id="myCanvas" width="600" height="300"></canvas>

In this example, the drawing surface is 600 by 300 pixels. If CSS scales it to appear 900 by 450 pixels, the internal dimensions are still 600 by 300. For a full clear, use canvas.width and canvas.height, rather than guessing from the displayed size or relying on getBoundingClientRect().

Using the CSS dimensions in clearRect() can leave a strip of old content behind or clear only part of the drawing surface. Check the actual values in your browser’s developer tools if the result looks unexpected:

console.log(canvas.width, canvas.height);
console.log(canvas.getBoundingClientRect());

Clear the Canvas When a Transform Is Active

Canvas transformations change how drawing coordinates are interpreted. If your code has translated, scaled, or rotated the context, the coordinates passed to clearRect() are affected too. As a result, a rectangle that should cover the whole canvas may clear the wrong area or fail to cover it completely.

You can temporarily reset the transformation to the identity matrix, clear the full canvas, and then restore the previous drawing state:

ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.restore();

save() and restore() preserve and reinstate the context’s drawing state, including its transform. The setTransform() call resets the transform for the clear operation. This is useful when your drawing code uses scaling or translation, but it is not always necessary for a simple canvas with no active transforms.

A clipping region can also restrict what gets cleared. If a clip is active, clearRect() only affects pixels inside that clip. The state-saving example will not remove an existing clip, because clipping is part of the saved drawing state. Structure your code so you clear before applying a clip, or restore the state that existed before the clip was created.

Reset the Canvas by Changing Its Dimensions

Setting the canvas’s width or height attribute clears its contents and resets the 2D context. For example:

canvas.width = canvas.width;

This technique clears the bitmap, but it also resets context settings and state. You may need to reapply the fill style, line width, font, transforms, compositing settings, and other configuration afterward. It can also interrupt drawing code that expects those settings to remain in place.

For that reason, prefer clearRect() when you only want to erase pixels. Changing the dimensions is more appropriate when you actually need to resize the drawing surface or deliberately reset the context. Avoid assigning the same width or height on every animation frame, since doing so repeatedly resets the context and can add unnecessary work.

Handle High-DPI Canvas Displays

On high-density screens, a canvas may need an internal drawing size larger than its CSS size to look sharp. A common approach is to multiply the displayed dimensions by the device pixel ratio, then scale the context so drawing coordinates can still match CSS pixels:

const canvas = document.querySelector("#myCanvas");
const ctx = canvas.getContext("2d");

const rect = canvas.getBoundingClientRect();
const dpr = window.devicePixelRatio || 1;

canvas.width = Math.round(rect.width * dpr);
canvas.height = Math.round(rect.height * dpr);

ctx.scale(dpr, dpr);

After scaling the context, the canvas’s internal dimensions are larger than the coordinate range used by your drawing code. If you call clearRect() using canvas.width and canvas.height while the scale is still active, those values are interpreted in scaled coordinates. Reset the transform before clearing the backing surface:

ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.restore();

Alternatively, if your code consistently draws in CSS-pixel coordinates, clear using the unscaled dimensions and the same coordinate system as your drawing. The important rule is to make the clearing rectangle match the context’s current transform and coordinate system.

Make the Canvas White Instead of Transparent

If you want a white canvas after clearing, use fillRect() to paint a white background. The distinction matters: clearRect() makes pixels transparent, while fillRect() draws a color over them.

ctx.fillStyle = "#ffffff";
ctx.fillRect(0, 0, canvas.width, canvas.height);

For a high-DPI canvas or one with an active transform, use the appropriate coordinate system, or temporarily reset the transform as shown earlier. If you are creating an animation with an opaque background, painting a solid rectangle at the start of each frame can be a straightforward alternative to clearing.

You can also set a background color with CSS, but that does not change the pixels stored in the canvas. This may be fine for a visual page background, but it is different from drawing a background into the canvas itself. The distinction can matter when exporting or processing the canvas image.

Common Reasons a Canvas Does Not Clear

  • The clearing dimensions are wrong: Use the internal values canvas.width and canvas.height, not CSS dimensions, unless your coordinate setup specifically requires them.
  • A transform is active: Reset the transform while clearing, then restore it if needed.
  • A clipping region is active: Clear before applying the clip, or restore an unclipped drawing state.
  • The canvas is being redrawn immediately: Another function may paint over the clear operation. Check the order of your drawing calls.
  • You expect a white background: Clearing produces transparency. Use fillRect() if you need an opaque color.
  • You resized the canvas: Changing its dimensions clears it but also resets context state, so reapply any required drawing settings.

When troubleshooting, confirm that you are clearing the same canvas you are drawing on, that the code runs after the canvas has loaded, and that no later function repaints the area. Logging the canvas dimensions and checking the order of drawing operations can quickly reveal common mistakes.

Conclusion

To clear an HTML canvas, get its 2D context and call clearRect(0, 0, canvas.width, canvas.height). This removes the drawing and leaves transparent pixels. Use the canvas’s internal dimensions, account for transforms and clipping, and clear at the start of each animation frame when you want to prevent old drawings from lingering. If you need a white background, draw a white rectangle instead. For most applications, clearRect() is the simplest and most reliable way to clear a canvas without resetting its context.


Disclaimer: Articles are written by Humans, AI or Both. Verify Important information.

Shrewdnia

Shrewdnia

Shrewdnia is a destination for curious minds seeking clarity, knowledge, and informed perspectives. Through insightful articles and practical guides our passionate team explores a wide range of topics designed to help readers understand the world around them, make smarter decisions, and stay informed in an ever-changing landscape.


💡 Every question sparks discovery, and every perspective enriches the conversation. Share your thoughts and insights in the comments 👇

Back to blog

Leave a comment

JOIN THE SHREWDNIA COMMUNITY FORUM

What do you think?

Have an opinion, experience, or question about this topic? Join the Shrewdnia Forum and share your thoughts with other readers.

Join the Forum →