html5 canvas – how to use ‘destination-out’ to clear out the most recently drawn shape only?

Suppose I have drawn a green rectangle and then a blue rectangle over it. I want to draw a circular hole in the blue rectangle so that the green rectangle underneath is visible through the hole.

enter image description here

I have tried using destination-out but it clears all shapes underneath:

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

ctx.fillStyle = "green";
ctx.fillRect(0, 0, 50, 100);

ctx.fillStyle = "blue";
ctx.fillRect(0, 0, 50, 50);

ctx.globalCompositeOperation = "destination-out";

ctx.beginPath();
ctx.arc(50 / 2 - 10 / 2, 50 / 2, 10, 0, Math.PI * 2);
ctx.fill();

ctx.globalCompositeOperation = "source-over";
<canvas
  id="canvas"
  width="500"
  height="200"
  style="background: black"
></canvas>

Answer

Create second canvas, add your blue rectangle to it, cut out circle and than merge it into first canvas:

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

ctx.fillStyle = "green";
ctx.fillRect(0, 0, 50, 100);


const canvasTemp = document.createElement("canvas");
const ctxTemp = canvasTemp.getContext("2d");

ctxTemp.fillStyle = "blue";
ctxTemp.fillRect(0, 0, 50, 50);

ctxTemp.globalCompositeOperation = "destination-out";

ctxTemp.beginPath();
ctxTemp.arc(50 / 2 - 10 / 2, 50 / 2, 10, 0, Math.PI * 2);
ctxTemp.fill();

ctxTemp.globalCompositeOperation = "source-over";

ctx.drawImage(canvasTemp, 0, 0);
<canvas
  id="canvas"
  width="500"
  height="200"
  style="background: black"
></canvas>