canvas画布demo
<!DOCTYPE html>
<html>
<head>
<title>demo</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
height: 100vh;
}
canvas {
display: block;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
let sakuraArray = [];
class Sakura {
constructor() {
this.x = Math.random() * canvas.width;
this.y = Math.random() * -canvas.height;
this.size = Math.random() * 10 + 10;
this.speed = 1.5;
this.angle = Math.random() * 45 + 45;
this.drift = Math.random() * -2.5 - 1.25;
this.alpha = 1;
this.img = new Image();
this.img.src = "./yinghua.png";
}
update() {
this.y += this.speed;
this.x += this.drift;
this.alpha -= 0.005;
}
draw() {
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate((this.angle * Math.PI) / 180);
ctx.globalAlpha = this.alpha;
ctx.drawImage(this.img, -this.size / 2, -this.size / 2, this.size, this.size);
ctx.restore();
}
}
function createSakura() {
sakuraArray.push(new Sakura());
}
function createSakuraMulti(count) {
for (let i = 0; i < count; i++) {
createSakura();
}
}
function drawSakuraMulti() {
for (let i = 0; i < sakuraArray.length; i++) {
sakuraArray[i].update();
sakuraArray[i].draw();
if (sakuraArray[i].alpha <= 0) {
sakuraArray.splice(i, 1);
createSakura();
}
}
}
function init() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
createSakuraMulti(50);
}
window.addEventListener("resize", function () {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawSakuraMulti();
requestAnimationFrame(animate);
}
init();
animate();
</script>