<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Canvas创意</title>
<script src="../libs/CloudOpen.js"></script>
<style>
body {
margin: 0px;
}
</style>
</head>
<body>
<div>
<canvas id="canvas-cloud"></canvas>
</div>
<script type="text/javascript">
(function () {
let cloudOpen = new CloudOpen();
let canvasCloud = document.getElementById("canvas-cloud");
cloudOpen.init(
() => {
function loop() {
cloudOpen.draw(() => {
cloudOpen.reset();
loop();
});
}
loop();
},
canvasCloud,
"https://file.idongjia.cn/T3F4CgB7_T1RCvBVdK.png",
"https://file.idongjia.cn/T3o7WgB7KT1RCvBVdK.png",
10
);
})();
</script>
</body>
</html>
class CloudOpen {
constructor() {
this.canv = null;
this.ctx = null;
this.i = 0;
this.speed = 0;
this.imgMask = new Image();
this.imgMask.crossOrigin = "";
this.img = new Image();
this.img.crossOrigin = "";
}
init(back, canvas, img, mask, speed = 10) {
this.speed = speed;
this.canv = canvas;
this.ctx = this.canv.getContext("2d");
this.i = 0;
this.img.onload = () => {
this.canv.width = this.img.naturalWidth;
this.canv.height = this.img.naturalHeight;
};
this.imgMask.onload = () => {
if (back) {
back();
}
};
this.img.src = img;
this.imgMask.src = mask;
}
step() {
let maskX = (this.canv.width - this.i) / 2;
let maskY = (this.canv.height - this.i) / 2;
this.ctx.clearRect(0, 0, this.canv.width, this.canv.height);
this.ctx.globalCompositeOperation = "source-over";
this.ctx.drawImage(this.imgMask, maskX, maskY, this.i, this.i);
this.ctx.globalCompositeOperation = "source-in";
this.ctx.drawImage(
this.img,
0,
0,
this.img.naturalWidth,
this.img.naturalHeight
);
}
reset() {
this.i = 0;
this.step();
}
draw(backFun = null) {
this.i += this.speed;
this.step();
let maxSize = Math.max(this.canv.width, this.canv.height);
if (this.i >= maxSize * 5) {
if (backFun) {
backFun();
}
} else {
window.requestAnimationFrame(() => {
this.draw(backFun);
});
}
}
}