vue实现粒子动画特效
Vue 实现粒子动画特效的方法
粒子动画通常通过 Canvas 或第三方库实现,以下是几种常见实现方式:
使用 Canvas 原生实现
通过 Vue 封装 Canvas 粒子动画组件:
<template>
<canvas ref="canvas" class="particle-canvas"></canvas>
</template>
<script>
export default {
mounted() {
this.initCanvas();
},
methods: {
initCanvas() {
const canvas = this.$refs.canvas;
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 粒子配置
const particles = [];
const particleCount = 100;
for (let i = 0; i < particleCount; i++) {
particles.push({
x: Math.random() * canvas.width,
y: Math.random() * canvas.height,
size: Math.random() * 5 + 1,
speedX: Math.random() * 3 - 1.5,
speedY: Math.random() * 3 - 1.5
});
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
particles.forEach(particle => {
particle.x += particle.speedX;
particle.y += particle.speedY;
// 边界检测
if (particle.x < 0 || particle.x > canvas.width) particle.speedX *= -1;
if (particle.y < 0 || particle.y > canvas.height) particle.speedY *= -1;
ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
ctx.beginPath();
ctx.arc(particle.x, particle.y, particle.size, 0, Math.PI * 2);
ctx.fill();
});
requestAnimationFrame(animate);
}
animate();
}
}
};
</script>
<style>
.particle-canvas {
position: fixed;
top: 0;
left: 0;
z-index: -1;
}
</style>
使用 particles.js 库
安装 particles.js 的 Vue 封装版本:
npm install particles.js vue-particles
组件使用方式:
<template>
<div id="app">
<vue-particles
color="#ffffff"
:particleOpacity="0.7"
:particlesNumber="80"
shapeType="circle"
:particleSize="4"
linesColor="#ffffff"
:linesWidth="1"
:lineLinked="true"
:lineOpacity="0.4"
:linesDistance="150"
:moveSpeed="3"
:hoverEffect="true"
hoverMode="grab"
:clickEffect="true"
clickMode="push"
/>
</div>
</template>
<script>
import VueParticles from 'vue-particles'
export default {
components: {
VueParticles
}
}
</script>
使用 tsParticles 库
安装 tsParticles(更现代的替代方案):
npm install tsparticles-slim
Vue 组件实现:
<template>
<div id="tsparticles"></div>
</template>
<script>
import { loadSlim } from "tsparticles-slim";
export default {
name: "ParticlesBackground",
mounted() {
this.initParticles();
},
methods: {
async initParticles() {
await loadSlim((engine) => {
return engine.load("tsparticles", {
particles: {
number: { value: 80 },
move: { enable: true },
opacity: { value: 0.5 },
size: { value: 3 },
links: {
enable: true,
distance: 150
}
}
});
}).then(({ container }) => {
container.loadCanvas("tsparticles", {
background: {
color: "#0d47a1"
}
});
});
}
}
};
</script>
性能优化建议
- 对于大量粒子(>1000),考虑使用 WebGL 渲染(如 three.js)
- 粒子数量根据设备性能动态调整
- 组件销毁时清除动画循环
- 移动设备减少粒子数量
以上方法可根据项目需求选择,原生 Canvas 适合定制化需求,而 particles.js/tsParticles 适合快速实现标准粒子效果。







