JSFiddle - React, Tailwind, and code Playground
by Dean Panayotov
JavaScript
canvas = document.getElementsByTagName('canvas')[0];
ctx = canvas.getContext('2d');
ctx.fillStyle = "#00FF00";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Create a canvas that we will use as a mask
var maskCanvas = document.createElement('canvas');
// Ensure same dimensions
maskCanvas.width = canvas.width;
maskCanvas.height = canvas.height;
var maskCtx = maskCanvas.getContext('2d');
// This color is the one of the filled shape
maskCtx.fillStyle = "black";
// Fill the mask
maskCtx.fillRect(0, 0, maskCanvas.width, maskCanvas.height);
// Set xor operation
maskCtx.globalCompositeOperation = 'xor';
//first circle
maskCtx.moveTo(maskCtx.canvas.width / 2 + 20, maskCtx.canvas.height / 2);
maskCtx.arc(maskCtx.canvas.width / 2 + 20, maskCtx.canvas.height / 2, 50, 0, Math.PI*2);
//second circle
maskCtx.moveTo(maskCtx.canvas.width / 2 - 20, maskCtx.canvas.height / 2);
maskCtx.arc(maskCtx.canvas.width / 2 - 20, maskCtx.canvas.height / 2, 50, 0, Math.PI*2);
maskCtx.fill();
// Draw mask on the image, and done !
ctx.globalAlpha = 0.5;
ctx.drawImage(maskCanvas, 0, 0);