vue实现烟花
Vue 实现烟花效果
在 Vue 中实现烟花效果可以通过结合 CSS 动画和 JavaScript 动态生成烟花元素。以下是具体实现方法:
动态生成烟花元素
通过 Vue 的 v-for 动态生成烟花粒子,每个粒子代表烟花的一个火花。在模板中添加一个容器用于放置烟花:
<template>
<div class="fireworks-container" @click="createFirework">
<div
v-for="(particle, index) in particles"
:key="index"
class="particle"
:style="{
left: particle.x + 'px',
top: particle.y + 'px',
backgroundColor: particle.color,
transform: `scale(${particle.size})`
}"
></div>
</div>
</template>
烟花粒子数据与动画
在 Vue 的 data 中定义粒子数组,并通过方法生成随机粒子属性:
data() {
return {
particles: []
}
},
methods: {
createFirework(event) {
const colors = ['#ff0000', '#ffff00', '#00ff00', '#00ffff', '#0000ff', '#ff00ff'];
const particleCount = 100;
for (let i = 0; i < particleCount; i++) {
const angle = Math.random() * Math.PI * 2;
const speed = Math.random() * 5 + 2;
const size = Math.random() * 0.5 + 0.5;
this.particles.push({
x: event.clientX,
y: event.clientY,
color: colors[Math.floor(Math.random() * colors.length)],
size,
vx: Math.cos(angle) * speed,
vy: Math.sin(angle) * speed
});
}
this.animateParticles();
},
animateParticles() {
const animation = setInterval(() => {
this.particles.forEach(particle => {
particle.x += particle.vx;
particle.y += particle.vy;
particle.vy += 0.1; // 重力效果
particle.size *= 0.99; // 粒子逐渐缩小
});
this.particles = this.particles.filter(p => p.size > 0.1);
if (this.particles.length === 0) {
clearInterval(animation);
}
}, 30);
}
}
CSS 样式
为烟花粒子添加基础样式和动画效果:
.fireworks-container {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
}
.particle {
position: absolute;
width: 6px;
height: 6px;
border-radius: 50%;
pointer-events: none;
transition: transform 0.1s ease-out;
}
优化与扩展
- 添加
requestAnimationFrame替代setInterval以获得更流畅的动画性能。 - 引入随机延迟和不同的粒子形状(如线条或星星)以增强视觉效果。
- 通过 Vue 的
transition-group实现粒子消失的渐隐效果。
完整示例可通过点击页面触发烟花爆炸,粒子会受重力影响下坠并逐渐消失。可根据需要调整粒子数量、颜色和运动参数以实现不同风格的烟花效果。







