JSFiddle - React, Tailwind, and code Playground
by twobomb three
HTML
<canvas width="500" height="500">
</canvas>
JavaScript
var url = "https://imagecdn1.luxnet.ua/zaxid/resources/photos/news/201710/1439426_1486240.jpg?201710201312";
var mask = [
[100,405],
[191,293],
[79,226],
[201,229],
[237,98],
[309,238],
[451,230],
[321,305],
[393,427],
[250,336],
];
var canvas = document.querySelector("canvas");
var ctx = canvas.getContext("2d");
var img = new Image();
var __opacity = 1;
var step = 0.02;
var animTimer;
img.src = url;
img.onload = draw;
function draw(){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.save();
ctx.globalAlpha=__opacity;
ctx.drawImage(img,0,0,canvas.width,canvas.height);
ctx.beginPath();
for(var i = 0 ; i< mask.length;i++)
if(i == 0)
ctx.moveTo(mask[i][0],mask[i][1]);
else
ctx.lineTo(mask[i][0],mask[i][1]);
ctx.closePath();
ctx.clip();
ctx.globalAlpha=1;
ctx.drawImage(img,0,0,canvas.width,canvas.height);
ctx.restore();
}
canvas.addEventListener("mouseenter",function(){
clearInterval(animTimer);
animTimer = setInterval(function(){
__opacity-=step;
if(__opacity < 0)
__opacity = 0;
draw();
if(__opacity== 0)
clearInterval(animTimer);
},30);
},false);
canvas.addEventListener("mouseleave",function(){
clearTimeout(animTimer);
animTimer = setInterval(function(){
__opacity+=step;
if(__opacity > 1)
__opacity = 1;
draw();
if(__opacity== 1)
clearInterval(animTimer);
},30);
},false);
/* canvas.onclick = function(e){
console.log("["+e.offsetX+","+e.offsetY+"],");
ctx.fillRect(e.offsetX,e.offsetY,5,5);
} */