vue实现粒子特效
使用vue-particles插件实现粒子特效
vue-particles是一个专为Vue设计的粒子效果插件,基于particles.js开发。安装方式如下:
npm install vue-particles
在main.js中全局引入:
import VueParticles from 'vue-particles'
Vue.use(VueParticles)
组件中使用示例:

<template>
<div id="app">
<vue-particles
color="#dedede"
:particleOpacity="0.7"
:particlesNumber="80"
shapeType="circle"
:particleSize="4"
linesColor="#dedede"
:linesWidth="1"
:lineLinked="true"
:lineOpacity="0.4"
:linesDistance="150"
:moveSpeed="3"
:hoverEffect="true"
hoverMode="grab"
:clickEffect="true"
clickMode="push"
/>
</div>
</template>
自定义配置参数
可通过修改以下参数调整粒子效果:
particles: {
number: { value: 80, density: { enable: true, value_area: 800 } },
color: { value: "#ffffff" },
shape: { type: "circle" },
opacity: { value: 0.5, random: false },
size: { value: 3, random: true },
line_linked: { enable: true, distance: 150, color: "#ffffff", opacity: 0.4, width: 1 },
move: { enable: true, speed: 6, direction: "none", random: false, straight: false }
}
使用原生Canvas实现
创建自定义Vue组件:

<template>
<canvas ref="canvas" class="particles-canvas"></canvas>
</template>
<script>
export default {
mounted() {
this.initParticles()
},
methods: {
initParticles() {
const canvas = this.$refs.canvas
const ctx = canvas.getContext('2d')
canvas.width = window.innerWidth
canvas.height = window.innerHeight
let 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 = -particle.speedX
}
if(particle.y < 0 || particle.y > canvas.height) {
particle.speedY = -particle.speedY
}
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>
.particles-canvas {
position: fixed;
top: 0;
left: 0;
z-index: -1;
}
</style>
性能优化建议
限制粒子数量在移动设备上自动减少:
const particleCount = window.innerWidth < 768 ? 50 : 100
添加resize事件处理:
window.addEventListener('resize', () => {
canvas.width = window.innerWidth
canvas.height = window.innerHeight
})
使用requestAnimationFrame替代setInterval确保流畅动画。考虑使用WebGL渲染器如three.js处理大规模粒子系统。






