particle.vue3
时间: 2025-05-16 22:48:26 浏览: 12
### Vue3 粒子效果实现方法或库
在前端开发领域,粒子动画是一种常见的视觉增强技术。对于基于 Vue3 的项目来说,可以利用一些现有的开源库来快速集成粒子效果。
#### 使用 `tsparticles` 实现粒子效果
`tsparticles` 是一个功能强大的 JavaScript 库,支持多种框架,包括 Vue.js 和 React[^1]。它提供了丰富的配置选项以及良好的性能优化能力。以下是通过该库在 Vue3 中实现粒子效果的方法:
安装依赖项:
```bash
npm install @tsparticles/vue --save
```
创建组件并引入插件:
```javascript
<template>
<Particles id="tsparticles" :options="particleOptions" />
</template>
<script>
import { Particles } from "@tsparticles/vue";
export default {
components: {
Particles,
},
data() {
return {
particleOptions: {
background: {
color: "#0d47a1",
},
fpsLimit: 60,
interactivity: {
events: {
onClick: {
enable: true,
mode: "push",
},
},
modes: {
push: {
quantity: 4,
},
},
},
particles: {
color: {
value: "#ffffff",
},
links: {
color: "#ffffff",
distance: 150,
enable: true,
opacity: 0.5,
width: 1,
},
collisions: {
enable: true,
},
move: {
direction: "none",
enable: true,
outModes: {
default: "bounce",
},
random: false,
speed: 2,
straight: false,
},
number: {
density: {
enable: true,
area: 800,
},
value: 80,
},
opacity: {
value: 0.5,
},
shape: {
type: "circle",
},
size: {
value: { min: 1, max: 5 },
},
},
detectRetina: true,
},
};
},
};
</script>
```
上述代码展示了如何使用 tsparticles 创建动态背景粒子效果,并允许用户点击屏幕生成新的粒子。
#### 自定义粒子效果实现方式
如果希望完全自定义粒子行为而不借助第三方库,则可以通过 HTML Canvas API 结合 Vue3 生命周期钩子函数完成。下面是一个简单的例子:
HTML 部分:
```html
<div ref="canvasContainer"></div>
```
JavaScript 部分:
```javascript
<template>
<div ref="canvasContainer"></div>
</template>
<script>
export default {
mounted() {
const canvas = document.createElement("canvas");
this.$refs.canvasContainer.appendChild(canvas);
const ctx = canvas.getContext("2d");
let w = (canvas.width = window.innerWidth);
let h = (canvas.height = window.innerHeight);
class Particle {
constructor(x, y) {
this.x = Math.random() * w;
this.y = Math.random() * h;
this.vx = Math.random() - 0.5;
this.vy = Math.random() - 0.5;
this.radius = Math.random() * 5 + 1;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
ctx.fillStyle = "white";
ctx.fill();
}
update() {
this.x += this.vx;
this.y += this.vy;
if (this.x >= w || this.x <= 0) this.vx *= -1;
if (this.y >= h || this.y <= 0) this.vy *= -1;
this.draw();
}
}
const particlesArray = [];
for (let i = 0; i < 100; i++) {
particlesArray.push(new Particle());
}
function animate() {
requestAnimationFrame(animate);
ctx.clearRect(0, 0, w, h);
for (const p of particlesArray) {
p.update();
}
}
animate();
window.addEventListener("resize", () => {
w = canvas.width = window.innerWidth;
h = canvas.height = window.innerHeight;
});
},
};
</script>
```
此示例演示了如何手动构建基本的粒子系统,其中每个粒子都有自己的速度向量和边界反弹逻辑[^2]。
阅读全文
相关推荐


















