JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>title</title>
</head>
<body>
<canvas id='canvas'></canvas>
<canvas id='canvas2'></canvas>
</body>
</html>
JavaScript
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'red';
ctx.fillRect(20, 20, 40, 40);
// I want to apply globalCompositeOperatoin = 'source-in'
// only on the blue and lime squares
ctx.fillStyle = 'blue';
ctx.fillRect(80, 20, 40, 40);
ctx.fillStyle = 'lime';
ctx.fillRect(90, 30, 40, 40);
// And then resume normal rendering
ctx.fillStyle = 'red';
ctx.fillRect(140, 20, 40, 40);
// Second canvas, the desired effect
const canvas2 = document.getElementById('canvas2');
const ctx2 = canvas2.getContext('2d');
ctx2.fillStyle = 'red';
ctx2.fillRect(20, 20, 40, 40);
ctx2.fillStyle = 'red';
ctx2.fillRect(140, 20, 40, 40);
ctx2.fillStyle = 'lime';
ctx2.fillRect(90, 30, 30, 30);