效果演示
部分源码如下
// 设置画布
import Firework from "./Firework";
const canvas = document.getElementById('fireworksCanvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 创建烟花
const fireworks = [];
// 随机生成烟花位置
function createFirework() {
const x = Math.random() * canvas.width;
fireworks.push(new Firework(canvas, ctx, x, canvas.height)); // 从画布底部发射
}
// 动画循环
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height); // 清除画布
// 创建随机烟花
if (Math.random() < 0.05) {
createFirework();
}
// 更新所有烟花
for (let i = 0; i < fireworks.length; i++) {
fireworks[i].update();
fireworks[i].draw();
}
// 动画递归
requestAnimationFrame(animate);
}
// 启动动画
animate();