<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>HTML5 Canvas图片上云雾弥漫驱散特效</title>
<style>
* {
margin: 0;
padding: 0;
}
body {
height: 100vh;
overflow: hidden;
background-color: #faf8f5;
}
#mycanvas,
#front {
width: 600px;
max-width: 100%;
height: auto;
display: block;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
cursor: pointer;
}
#mycanvas {
display: none;
}
</style>
</head>
<body>
<!-- 点击图片,触发炫酷的图片蒙层雾化特效 -->
<canvas id="mycanvas"></canvas>
<img id="front" src="images/photo1.png">
<script>
const front = document.getElementById("front"),
canv = document.getElementById("mycanvas"),
ctx = canv.getContext("2d"),
img = new Image(),
imgMask = new Image();
img.src = "images/photo1.png";
imgMask.src = "images/cloud-texture.png";
let i = 0;
function draw() {
i += 10;
let maskX = (canv.width - (70 + i)) / 2,
maskY = (canv.height - (40 + i)) / 2;
ctx.clearRect(0, 0, canv.width, canv.height);
ctx.globalCompositeOperation = "source-over";
ctx.drawImage(imgMask, maskX, maskY, 70 + i, 40 + i);
ctx.globalCompositeOperation = "source-in";
ctx.drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight);
window.requestAnimationFrame(draw);
}
img.onload = function() {
canv.width = img.naturalWidth;
canv.height = img.naturalHeight;
}
front.onclick = function() {
front.style.display = "none";
canv.style.display = "block";
draw();
}
canv.onclick = function() {
i = 0;
draw();
}
</script>
</body>
</html>