本文发布于 2年前,其中的信息可能已发生变化,请结合实际情况参考。
分享我写的樱花飘落Canvas实现
博客上的樱花飘落效果是怎么做的?今天把源码分享出来~ 🌸
效果展示
樱花花瓣从屏幕上方飘落,带旋转和摆动,超治愈。

实现思路
用Canvas绘制花瓣,每个花瓣是一个对象,包含位置、速度、旋转角度等属性。
核心代码
javascript
class Petal {
constructor() {
this.x = Math.random() * canvas.width;
this.y = -20;
this.size = Math.random() * 8 + 6;
this.speed = Math.random() * 1.5 + 0.5;
this.angle = 0;
this.swing = Math.random() * 2 - 1;
}
update() {
this.y += this.speed;
this.x += Math.sin(this.y * 0.02) * this.swing;
this.angle += 0.02;
}
draw(ctx) {
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.angle);
ctx.fillStyle = '#ffb7c5';
ctx.beginPath();
ctx.ellipse(0, 0, this.size, this.size * 0.6, 0, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
}
}
下载源码
完整版支持花瓣数量控制、风向、点击交互:
Canvas动画的核心就是「每帧更新+重绘」,掌握了这个思路什么动画都能做。
把樱花飘落加到你的博客上吧~ ✨


评论 2