vue实现点击烟花
Vue实现点击烟花效果
在Vue中实现点击烟花效果,可以通过监听点击事件并动态生成烟花元素。以下是两种实现方式:

方式一:使用CSS动画和动态元素
<template>
<div class="fireworks-container" @click="createFirework">
<div
v-for="(firework, index) in fireworks"
:key="index"
:style="firework.style"
class="firework"
></div>
</div>
</template>
<script>
export default {
data() {
return {
fireworks: []
}
},
methods: {
createFirework(e) {
const colors = ['#ff0000', '#00ff00', '#0000ff', '#ffff00', '#ff00ff']
for (let i = 0; i < 50; i++) {
const angle = Math.random() * Math.PI * 2
const velocity = 5 + Math.random() * 7
const size = 3 + Math.random() * 5
this.fireworks.push({
style: {
left: `${e.clientX}px`,
top: `${e.clientY}px`,
backgroundColor: colors[Math.floor(Math.random() * colors.length)],
transform: `translate(${Math.cos(angle) * velocity * 10}px, ${Math.sin(angle) * velocity * 10}px)`,
width: `${size}px`,
height: `${size}px`,
opacity: 1
}
})
}
setTimeout(() => {
this.fireworks = []
}, 1000)
}
}
}
</script>
<style>
.fireworks-container {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
}
.firework {
position: absolute;
border-radius: 50%;
transition: transform 1s ease-out, opacity 1s ease-out;
}
</style>
方式二:使用Canvas实现高性能烟花
<template>
<canvas
ref="canvas"
@click="launchFirework"
style="position: fixed; top: 0; left: 0; width: 100%; height: 100%;"
></canvas>
</template>
<script>
export default {
mounted() {
this.canvas = this.$refs.canvas
this.ctx = this.canvas.getContext('2d')
this.fireworks = []
this.particles = []
this.canvas.width = window.innerWidth
this.canvas.height = window.innerHeight
window.addEventListener('resize', () => {
this.canvas.width = window.innerWidth
this.canvas.height = window.innerHeight
})
this.animate()
},
methods: {
launchFirework(e) {
const x = e.clientX
const y = e.clientY
this.fireworks.push({
x: x,
y: y,
particles: Array(50).fill().map(() => ({
x: x,
y: y,
vx: Math.random() * 6 - 3,
vy: Math.random() * 6 - 3,
color: `hsl(${Math.random() * 360}, 100%, 50%)`,
size: Math.random() * 3 + 1,
life: 100
}))
})
},
animate() {
this.ctx.fillStyle = 'rgba(0, 0, 0, 0.1)'
this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height)
this.fireworks.forEach(fw => {
fw.particles.forEach(p => {
p.x += p.vx
p.y += p.vy
p.life--
this.ctx.fillStyle = p.color
this.ctx.globalAlpha = p.life / 100
this.ctx.beginPath()
this.ctx.arc(p.x, p.y, p.size, 0, Math.PI * 2)
this.ctx.fill()
})
})
this.fireworks = this.fireworks.filter(fw =>
fw.particles.some(p => p.life > 0)
)
requestAnimationFrame(this.animate)
}
}
}
</script>
实现要点
第一种方式使用Vue的动态渲染和CSS动画,适合简单的烟花效果。第二种方式使用Canvas,性能更好,适合复杂的烟花效果和大量粒子。
两种方式都可以通过调整参数来改变烟花效果:
- 粒子数量影响烟花密度
- 粒子速度影响烟花扩散范围
- 粒子大小影响视觉效果
- 颜色可以随机生成或使用特定配色方案
可以根据实际需求选择适合的实现方式,或结合两者优势创建更丰富的交互效果。







