vue实现烟花效果
Vue 实现烟花效果的方法
在Vue中实现烟花效果可以通过结合Canvas绘图和动画技术来完成。以下是一种常见的实现方式:
创建Vue组件
新建一个名为Fireworks.vue的组件,核心逻辑如下:

<template>
<canvas ref="canvas" class="fireworks-canvas"></canvas>
</template>
<script>
export default {
mounted() {
this.initCanvas();
this.startFireworks();
},
methods: {
initCanvas() {
this.canvas = this.$refs.canvas;
this.ctx = this.canvas.getContext('2d');
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
window.addEventListener('resize', () => {
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
});
},
startFireworks() {
const particles = [];
const particleCount = 150;
function Particle(x, y) {
this.x = x;
this.y = y;
this.color = `hsl(${Math.random() * 360}, 100%, 50%)`;
this.radius = Math.random() * 2 + 1;
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;
}
function createFirework(x, y) {
for (let i = 0; i < particleCount; i++) {
particles.push(new Particle(x, y));
}
}
function animate() {
requestAnimationFrame(animate);
this.ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
particles.forEach((particle, index) => {
particle.velocity.y += 0.05;
particle.x += particle.velocity.x;
particle.y += particle.velocity.y;
particle.alpha -= particle.decay;
this.ctx.beginPath();
this.ctx.arc(particle.x, particle.y, particle.radius, 0, Math.PI * 2);
this.ctx.fillStyle = particle.color.replace(')', `, ${particle.alpha})`).replace('hsl', 'hsla');
this.ctx.fill();
if (particle.alpha <= 0) {
particles.splice(index, 1);
}
});
}
this.canvas.addEventListener('click', (e) => {
createFirework(e.clientX, e.clientY);
});
animate.call(this);
}
}
};
</script>
<style>
.fireworks-canvas {
position: fixed;
top: 0;
left: 0;
z-index: 9999;
pointer-events: none;
}
</style>
使用组件
在需要显示烟花效果的页面中引入并使用该组件:
<template>
<div>
<Fireworks />
<!-- 其他页面内容 -->
</div>
</template>
<script>
import Fireworks from '@/components/Fireworks.vue';
export default {
components: {
Fireworks
}
};
</script>
自定义烟花效果
可以通过修改以下参数来自定义烟花效果:

particleCount:控制烟花粒子数量decay值:调整粒子消失速度velocity:改变粒子飞散速度color:使用不同的颜色生成方式
自动触发烟花
如果需要自动触发而非点击触发,可以添加定时器:
// 在startFireworks方法中添加
setInterval(() => {
const x = Math.random() * this.canvas.width;
const y = Math.random() * this.canvas.height * 0.5;
createFirework(x, y);
}, 1000);
性能优化
对于大量烟花效果,可以考虑以下优化措施:
- 限制同时存在的粒子数量
- 使用Web Worker处理粒子计算
- 降低动画帧率
- 使用requestAnimationFrame的节流版本
这种方法创建的烟花效果完全基于Canvas,不依赖任何外部库,性能良好且可高度自定义。






