前言
- 在公司某项目登录界面见到粒子动画背景,也想将这个动画效果用在自己的项目上,起初以为直接安装
vue-particles
就可以了,结果自己的项目是Vue3的,不兼容。根据网上调研,在Vue3中可以使用particles.vue3
实现这个粒子动画
particles.vue3官网
Demos
- 就是一个演示,在里面可以自己更改一些配置
Presets
- 就是预设的动画,点进去可以看到效果
API Docs
- 文档
CodePen
- 代码笔,在这里面有很多样例,可以直接修改成自己想要的样子
安装
npm install particles.vue3
配置
- 在
main.ts
文件中加入以下代码
import { createApp } from 'vue'
import Particles from 'particles.vue3'
const app = createApp(App)
app.use(Particles)
app.mount('#app')
- 加入后会有以下报错
- 需要在
env.d.ts
文件中进行声明,报错解决
declare module 'particles.vue3';
使用
-
完成以上即可在你需要的页面进行使用了
-
比如说,我需要在登录页面进行使用
- 直接使用
Particles
组件
- 直接使用
-
在
login.vue
文件中
<template>
<div class="login">
<Particles id="tsparticles" class="login__particles" :options="particles" />
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import { particles } from './config/particles-config'
export default defineComponent({
setup() {
return {
particles
}
}
})
</script>
<style scoped lang="less">
.login {
flex: auto;
display: flex;
align-items: center;
justify-content: space-around;
position: relative;
height: 100%;
width: 100%;
overflow: hidden;
&__particles {
height: 100%;
width: 100%;
background-size: cover;
background-repeat: no-repeat;
background-image: url('../../assets/img/jiguang.jpeg');
}
}
</style>
-
将配置单独写到文件
particles-config.ts
,代码看起来更简洁-
在
login.vue
同级目录新建文件夹config
,再剪particles-config.ts
-
很多配置项没有逐一搞懂,要是有兴趣的话,自己看看官方文档吧
-
也可以根据英文意思大概猜一猜是什么配置
-
// 背景动画设置
export const particles = {
fpsLimit: 60,
interactivity: {
detectsOn: 'canvas',
events: {
onClick: { // 开启鼠标点击的效果
enable: true,
mode: 'push'
},
onHover: { // 开启鼠标悬浮的效果(线条跟着鼠标移动)
enable: true,
mode: 'grab'
},
resize: true
},
modes: { // 配置动画效果
bubble: {
distance: 400,
duration: 2,
opacity: 0.8,
size: 40
},
push: {
quantity: 4
},
grab: {
distance: 200,
duration: 0.4
},
attract: { // 鼠标悬浮时,集中于一点,鼠标移开时释放产生涟漪效果
distance: 200,
duration: 0.4,
factor: 5
}
}
},
particles: {
color: {
value: '#6AECFF' // 粒子点的颜色
},
links: {
color: '#6AECFF', // 线条颜色
distance: 150,
enable: true,
opacity: 0.5, // 不透明度
width: 2 // 线条宽度
},
collisions: {
enable: true
},
move: {
attract: { enable: false, rotateX: 600, rotateY: 1200 },
bounce: false,
direction: 'none',
enable: true,
out_mode: 'out',
random: false,
speed: 1, // 移动速度
straight: false
},
number: {
density: {
enable: true,
value_area: 800
},
value: 80
},
opacity: {
value: 0.5
},
shape: {
type: 'circle'
},
size: {
random: true,
value: 5
}
},
detectRetina: true
}
- 效果如下所示