js 实现烟花
实现烟花效果的 JavaScript 代码
以下是一个使用 Canvas 和 JavaScript 实现烟花效果的完整代码示例。该代码会创建多个烟花粒子,模拟爆炸和下落的效果。
// 获取 Canvas 元素和上下文
const canvas = document.getElementById('fireworksCanvas');
const ctx = canvas.getContext('2d');
// 设置 Canvas 大小为窗口大小
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 烟花粒子类
class Particle {
constructor(x, y, color) {
this.x = x;
this.y = y;
this.color = color;
this.velocity = {
x: (Math.random() - 0.5) * 8,
y: (Math.random() - 0.5) * 8
};
this.alpha = 1;
this.decay = Math.random() * 0.015 + 0.01;
this.size = Math.random() * 3 + 1;
}
update() {
this.velocity.y += 0.05; // 重力
this.x += this.velocity.x;
this.y += this.velocity.y;
this.alpha -= this.decay;
}
draw() {
ctx.save();
ctx.globalAlpha = this.alpha;
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
ctx.restore();
}
}
// 烟花数组
let particles = [];
// 创建烟花
function createFirework(x, y) {
const particleCount = 150;
const hue = Math.floor(Math.random() * 360);
for (let i = 0; i < particleCount; i++) {
particles.push(new Particle(x, y, `hsl(${hue}, 100%, 50%)`));
}
}
// 动画循环
function animate() {
requestAnimationFrame(animate);
ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < particles.length; i++) {
particles[i].update();
particles[i].draw();
if (particles[i].alpha <= 0) {
particles.splice(i, 1);
i--;
}
}
}
// 点击或自动创建烟花
canvas.addEventListener('click', (e) => {
createFirework(e.clientX, e.clientY);
});
// 自动随机生成烟花
setInterval(() => {
const x = Math.random() * canvas.width;
const y = Math.random() * canvas.height / 2;
createFirework(x, y);
}, 1000);
// 开始动画
animate();
HTML 部分
需要将以下 HTML 代码添加到页面中:
<!DOCTYPE html>
<html>
<head>
<title>烟花效果</title>
<style>
body {
margin: 0;
overflow: hidden;
background-color: #000;
}
canvas {
display: block;
}
</style>
</head>
<body>
<canvas id="fireworksCanvas"></canvas>
<script src="fireworks.js"></script>
</body>
</html>
代码说明
-
Canvas 设置:代码首先获取 Canvas 元素并设置其大小为窗口大小,为绘制烟花做好准备。
-
粒子类:
Particle类定义了每个烟花粒子的属性,包括位置、速度、颜色、透明度和大小。update方法处理粒子的运动逻辑,draw方法负责绘制粒子。 -
烟花创建:
createFirework函数在指定位置创建多个随机颜色的粒子,模拟烟花爆炸效果。
-
动画循环:
animate函数是核心动画循环,清除画布并更新、绘制所有粒子,移除透明度为0的粒子。 -
交互:代码支持点击触发烟花和自动随机生成烟花两种模式。
自定义选项
-
调整粒子数量:修改
particleCount的值可以改变每个烟花的粒子数量,数值越大效果越密集。
-
改变颜色:使用 HSL 颜色模式可以轻松生成鲜艳的颜色,调整
hue值范围或使用固定颜色数组可以实现不同效果。 -
调整重力:修改
this.velocity.y += 0.05中的数值可以改变粒子下落速度,数值越大下落越快。 -
改变烟花大小:调整
this.size的计算公式可以改变粒子大小,实现不同风格的烟花效果。 -
调整消失速度:修改
this.decay的计算公式可以控制粒子消失的速度,数值越大消失越快。
这个实现提供了基础的烟花效果,可以根据需要进一步扩展,如添加声音效果、不同类型的烟花图案或更复杂的物理模拟。






