I am trying to create a moon shape with canvas. Therefor I created two circles: One being filled with my color, another one being subtracted using globalCompositionOperation: "destination-out".
const moonCanvas = createCanvas(WIDTH, HEIGHT);
const moonCtx = canvas.getContext("2d");
moonCtx.beginPath();
moonCtx.arc(WIDTH / 2, HEIGHT / 2, HEIGHT / 4, 0, 2 * Math.PI);
moonCtx.fill();
moonCtx.globalCompositeOperation = "destination-out";
moonCtx.beginPath();
moonCtx.arc(WIDTH / 2 + 30, HEIGHT / 2, HEIGHT / 4, 0, 2 * Math.PI);
moonCtx.fill();
Here's a fiddle with a minimal reproduction: https://jsfiddle.net/h2qbytzn/
The problem now is that there is "explicit" transparency added to the canvas by this operation. Whenever I want to add the moon to another canvas, it also includes the transparent parts and thus overwrites what is already there on there canvas.
Is there a way to import the canvas contents while ignoring the transparent parts?
What worked for me now is creating a second canvas, painting my objects there and merging them into the original canvas with drawImage:
const c2 = createCanvas(WIDTH, HEIGHT);
const ctx2 = c2.getContext("2d");
ctx2.fillStyle = "yellow";
ctx2.beginPath();
ctx2.arc(WIDTH / 2, HEIGHT / 2, HEIGHT / 4, 0, 2 * Math.PI);
ctx2.fill();
ctx2.globalCompositeOperation = "destination-out";
ctx2.beginPath();
ctx2.arc(WIDTH / 2 + 30, HEIGHT / 2 - 15, HEIGHT / 4, 0, 2 * Math.PI);
ctx2.fill();
ctx.drawImage(c2, 0, 0); // merging the canvas, not its context!