A scene paints a background, clears a region, and redraws a marker in a new position.

Program

Canvas does not remember shapes as objects. To change a scene, code clears pixels and draws the new state.

clear_redraw.html
Visuals: captured from real browser rendering
<canvas id="stage" width="360" height="210"></canvas>
<script>
  const ctx = stage.getContext("2d");
  ctx.fillStyle = "#e0f2fe";
  ctx.fillRect(0, 0, 360, 210);
  ctx.fillStyle = "#1d4ed8";
  ctx.fillRect(54, 82, 54, 54);
  ctx.clearRect(40, 70, 90, 80);
  ctx.fillRect(210, 82, 54, 54);
</script>
  1. Paint the scene background.

    A pale blue background fills the canvas.
    The first fillRect paints the whole scene.
  2. Draw the marker at the first position.

    A blue square appears on the left.
    The marker is just pixels on top of the background.
  3. Clear the old marker area.

    The left marker disappears and the cleared area is transparent white.
    clearRect removes pixels from a rectangular region.
  4. Draw the marker at the new position.

    The blue square appears on the right.
    Redrawing creates the new scene state.
clearRect clearRect clears pixels in a rectangle.
redraw A canvas scene changes by clearing and drawing pixels again.