To completely clear an HTML5 <canvas> before redrawing, call ctx.clearRect(0, 0, canvas.width, canvas.height) on its 2D rendering context—or set canvas.width = canvas.width when you also want to reset all canvas state (transforms, fill/stroke styles, line widths, shadows, and clipping paths) back to defaults. clearRect(0, 0, canvas.width, canvas.height) erases pixels to transparent black (rgba(0, 0, 0, 0)) quickly without resetting context state, while setting canvas.width forces a full backing-store reset that can be slower and discards active transforms and styles.


1. Clearing Pixels Cleanly with ctx.clearRect()

Use ctx.clearRect(0, 0, canvas.width, canvas.height) at the start of your render loop when you want fast pixel clearing while keeping your current transforms, styles, and clipping setup:

// Clear the entire canvas pixel buffer while preserving 2D context state
function clearCanvas(canvas, ctx) {
  if (!(canvas instanceof HTMLCanvasElement) || !ctx) {
    throw new TypeError("Expected a valid canvas element and 2D context.");
  }

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

// Example usage inside a render loop:
const canvas = document.querySelector("#scene");
const ctx = canvas.getContext("2d");

function renderFrame(x) {
  clearCanvas(canvas, ctx);
  ctx.fillStyle = "#2563eb";
  ctx.fillRect(x, 40, 60, 60);
}

renderFrame(20);
  • Fast and state-preserving: Keeps your existing ctx.scale(), ctx.translate(), ctx.fillStyle, and ctx.lineWidth intact across frames.
  • Erases to transparent: Clears pixels to rgba(0, 0, 0, 0); fill a background rectangle afterward if you want a solid backdrop.

2. Clearing with Active Transforms (ctx.save() / ctx.restore())

If your drawing code applies translations, rotations, or scaling before clearing, clearRect(0, 0, canvas.width, canvas.height) uses the current transform matrix—so temporarily reset the transform with ctx.setTransform(1, 0, 0, 1, 0, 0) (or wrap transforms in save() / restore()) to guarantee the entire backing store is cleared:

// Clear the full backing store even when transforms are active
function clearCanvasIgnoringTransform(canvas, ctx) {
  ctx.save();
  ctx.setTransform(1, 0, 0, 1, 0, 0);
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.restore();
}

// Example usage:
// ctx.scale(2, 2);
// clearCanvasIgnoringTransform(canvas, ctx);
  • Prevents partial clears: A scaled or translated context can cause clearRect(0, 0, canvas.width, canvas.height) to miss part of the canvas or clear outside bounds.
  • Pair save() with restore(): Prevents state drift from accumulating over repeated frames.

3. Resetting Both Pixels and Context State via canvas.width

Reassigning canvas.width = canvas.width (or updating canvas.width and canvas.height when resizing for devicePixelRatio) clears the bitmap and resets all context state to defaults, making it useful on resize or full state resets—though less ideal for tight per-frame animation loops:

// Sync canvas pixel resolution with CSS size and DPR (which also clears & resets state)
function resizeCanvasToDisplaySize(canvas, ctx) {
  const dpr = window.devicePixelRatio || 1;
  const rect = canvas.getBoundingClientRect();
  const targetWidth = Math.max(1, Math.round(rect.width * dpr));
  const targetHeight = Math.max(1, Math.round(rect.height * dpr));

  if (canvas.width !== targetWidth || canvas.height !== targetHeight) {
    canvas.width = targetWidth;
    canvas.height = targetHeight;
  }

  ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
}

// Example usage:
// resizeCanvasToDisplaySize(canvas, ctx);
  • Resets context state: Reassigning canvas.width wipes styles, paths, shadows, and transforms back to initial defaults.
  • Prefer clearRect() per frame: During steady animation, clearRect() avoids reallocating/resetting context properties every tick.