vue实现烟花效果
使用 Canvas 绘制基础烟花
在 Vue 中创建一个 Canvas 元素,通过 JavaScript 动态绘制烟花效果。初始化 Canvas 并设置其宽高为全屏,监听点击事件触发烟花动画。
<template>
<canvas ref="canvas" @click="createFirework"></canvas>
</template>
<script>
export default {
mounted() {
this.canvas = this.$refs.canvas;
this.ctx = this.canvas.getContext('2d');
this.resizeCanvas();
window.addEventListener('resize', this.resizeCanvas);
},
methods: {
resizeCanvas() {
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
},
createFirework(e) {
const x = e.clientX;
const y = e.clientY;
this.animateFirework(x, y);
}
}
}
</script>
烟花粒子动画实现
定义粒子类并实现扩散效果。每个烟花由多个粒子组成,粒子以随机角度和速度向外扩散,同时受到重力影响下坠。
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;
}
update() {
this.velocity.y += 0.05; // 重力
this.x += this.velocity.x;
this.y += this.velocity.y;
this.alpha -= this.decay;
return this.alpha > 0;
}
draw(ctx) {
ctx.save();
ctx.globalAlpha = this.alpha;
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, 2, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
}
}
动画循环与性能优化
使用 requestAnimationFrame 实现平滑动画,管理粒子数组并定期清理已完成动画的粒子以避免内存泄漏。
animateFirework(x, y) {
const particles = [];
const hue = Math.floor(Math.random() * 360);
const color = `hsl(${hue}, 100%, 50%)`;
for (let i = 0; i < 150; i++) {
particles.push(new Particle(x, y, color));
}
const animate = () => {
this.ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
for (let i = 0; i < particles.length; i++) {
if (particles[i].update()) {
particles[i].draw(this.ctx);
} else {
particles.splice(i, 1);
i--;
}
}
if (particles.length > 0) {
requestAnimationFrame(animate);
}
};
animate();
}
添加自动发射功能
通过定时器实现自动发射烟花效果,增强视觉体验。可以设置随机位置或跟随鼠标轨迹发射。
data() {
return {
autoFireInterval: null
};
},
methods: {
startAutoFire() {
this.autoFireInterval = setInterval(() => {
const x = Math.random() * this.canvas.width;
const y = Math.random() * this.canvas.height / 2;
this.animateFirework(x, y);
}, 800);
},
stopAutoFire() {
clearInterval(this.autoFireInterval);
}
},
mounted() {
// ...其他初始化代码
this.startAutoFire();
},
beforeDestroy() {
this.stopAutoFire();
window.removeEventListener('resize', this.resizeCanvas);
}
样式优化与响应式处理
为 Canvas 添加基础样式确保全屏显示,并通过 CSS 处理层级关系。
<style scoped>
canvas {
position: fixed;
top: 0;
left: 0;
z-index: -1;
background: #000;
}
</style>
以上实现提供了完整的 Vue 烟花效果组件,包含点击交互、自动发射、粒子动画和性能优化等核心功能。可根据需要调整粒子数量、颜色、速度和重力等参数获得不同视觉效果。







