body {
fontfamily: Arial, sansserif;
margin: 0;
padding: 0;
backgroundcolor: f8f8f8;
}
canvas {
display: block;
position: fixed;
top: 0;
left: 0;
pointerevents: none;
}
// 创建画布
const canvas = document.getElementById('sakura');
const ctx = canvas.getContext('2d');
// 设置画布大小
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 定义樱花数量
const numSakura = 50;
const sakuraArray = [];
// 定义樱花对象
class Sakura {
constructor() {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.radius = Math.random() * 5 5;
this.speed = Math.random() * 1 0.5;
this.angle = Math.random() * 360;
this.drift = Math.random() * 1 0.5;
}
// 更新樱花位置
update() {
this.x = Math.cos(this.angle) * this.speed;
this.y = Math.sin(this.angle) * this.speed;
this.angle = this.drift;
// 重新生成樱花
if (this.x < 0 || this.x > canvas.width || this.y > canvas.height) {
this.x = Math.random() * canvas.width;
this.y = 10;
}
}
// 绘制樱花
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = 'FFC0CB';
ctx.fill();
}
}
// 初始化樱花数组
function init() {
for (let i = 0; i < numSakura; i ) {
sakuraArray.push(new Sakura());
}
}
// 动画循环
function animate() {
requestAnimationFrame(animate);
ctx.clearRect(0, 0, canvas.width, canvas.height);
sakuraArray.forEach(sakura => {
sakura.update();
sakura.draw();
});
}
// 初始化并开始动画
init();
animate();