JSFiddle - React, Tailwind, and code Playground
HTML
<div style="margin: 100px 0 0 100px">
<div id="to-be-masked">
Mask me
</div>
<div>
CSS
#to-be-masked {
width: 200px; height: 300px;
}
#canvas {
position: absolute;
top: 0; left: 0;
}
JavaScript
// Create the canvas element
var canvas = $('<canvas id="canvas"/>');
// Append the masks to the body element
var body = $('body');
body.append(canvas)
// Get the dimensions of the element to mask
var elementToMask = $('#to-be-masked');
var offset = elementToMask.offset();
var top = offset.top;
var left = offset.left;
var width = elementToMask.width();
var height = elementToMask.height();
var winWidth = $(window).width();
var winHeight = $(window).height();
// Configure the canvas
var context = canvas.get(0).getContext("2d");
canvas.attr('width', winWidth);
canvas.attr('height', winHeight);
context.fillStyle = 'rgba(0, 0, 0, .5)';
context.fillRect(0,0, winWidth, winHeight);
// Clear a rectangle in the canvas
context.clearRect(left, top, width, height);