JSFiddle - React, Tailwind, and code Playground
HTML
<canvas width="400" height="400" id="canvas"></canvas>
JavaScript
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var image = new Image;
image.addEventListener('load', function(){
ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
ctx.fillStyle = "rgba(0, 0, 0, 0.5)";
ctx.fillRect(0, 0, 870, 500);
// Use save and restore to make sure the canvas restores its non-clipping path setup after clipping
ctx.save();
makePath();
// Use the path just created as a clipping path
ctx.clip();
// Draw anywhere in the image, only inside the clipping path will be drawn
ctx.drawImage(image,0,0, canvas.width, canvas.height);
// restore so you can draw outside the clipping path again
ctx.restore();
});
function makePath() {
ctx.beginPath();
ctx.moveTo(10, 10);
ctx.lineTo(100,50);
ctx.lineTo(100, 100);
ctx.lineTo(200, 150);
ctx.lineTo(10, 150);
ctx.closePath();
}
canvas.onclick = function(e) {
var rect = this.getBoundingClientRect(),
x = e.clientX - rect.left,
y = e.clientY - rect.top;
makePath();
if (!ctx.isPointInPath(x, y)) alert("Outside");
};
image.src = 'http://www.marinadivenezia.it/media/467/w-876/h-506/00-MAPPA-2015-GENERICA.jpeg';