效果
先看效果图,你是否有这么一个冲动,将自己的网站或者开发的网站加入一些动态的背景粒子,这里有一个开箱即用的插件,帮助你完成这样一个操作,先看一下效果图
感觉是不是很好看,这里就介绍怎么在项目中使用。
使用
开始
首先介绍该插件的地址 particles.js,具体api以及配置这里都有,如果你只是想自定义使用,它有一个自定义属性的连接,particles.js自定义样式 ,通过该网站就又可以自定义我们需要的效果。
使用npm下载依赖,大家都明白的。如果不想下载依赖的可以使用cdn。
NPM
npm install particles.js
CDN
<script src="https://cdn.jsdelivr.net/npm/particles.js@2.0.0/particles.min.js"></script>
应用
首先就是将配置好的样式下载到本地,相信下载这个都没问题的,下载的文件是一个.json的文件,我将该文件放入到我项目的静态公共资源目录下,具体放入哪一个位置,大家可以根据自己项目来。
封装
这里我将他封装成一个公共组件,应用在各种页面中。
<template>
<!-- particles插件的封装 -->
<div class="particles-js-box">
<div id="particles-js"></div>
</div>
</template>
<script>
import particlesConfig from "@/assets/js/particlesjs-config.json";
export default {
name: 'Particles',
data() {
return {
}
},
components: {
},
mounted() {
this.init();
},
methods: {
// 初始化应用,其实就是获取到某个标签的dom,然后通过particlesJS函数完成dom的修饰,将下载的配置文件引入到dom,从而达到动态的效果,
// 底层代码有时间再研究
// particlesJS(dom-id, path-json, callback (optional));这是该函数的参数配置,相信通过字面意思就可以看出参数都是些什么吧
init() {
// eslint-disable-next-line no-undef
particlesJS("particles-js", particlesConfig)
}
}
}
</script>
<style lang='less' scoped>
.particles-js-box {
position: fixed;
width: 100%;
height: 100%;
top: 0;
left: 0;
z-index: -1; //这里建议层级设为-1,但-1可能会导致被其他元素遮挡
#particles-js {
background-color: @header-background-color;
width: 100%;
height: 100%;
}
}
</style>
使用
在页面中这样使用就可以了。可以在你的入口文件中使用,也就是App.vue文件中,根据项目需要达到的效果进行使用即可。我这里就简单的我的错误页面中使用一下。
<template>
<div class="error-wrap flex-column">
<!-- 在页面中使用 -->
<Particles></Particles>
<div class="error-box">
<img src="../../assets/images/404.png" alt="" />
<h4>出错了哦!!!</h4>
<button class="button-style" @click="back">返回</button>
</div>
</div>
</template>
<script>
// 导入组件
import Particles from '@/components/Particles'
export default {
name: 'Error',
data() {
return {
}
},
components: {
// 注册组件
Particles
},
mounted() {
},
methods: {
// 返回上一次正确的路由
back() {
this.$router.go(-1)
}
}
}
</script>
<style lang='less' scoped>
.error-wrap {
height: calc(100vh - 68px);
padding-top: 60px;
.error-box {
display: flex;
-webkit-box-orient: vertical;
flex-direction: column;
flex: 1 1 auto;
justify-content: center;
align-items: center;
img {
width: 20rem;
height: 20rem;
margin-bottom: 1.5rem;
}
h4 {
font-size: 1.5rem;
color: @color-dark;
}
.button-style {
background-color: @color-dark;
color: @color-blank;
font-size: 1.2rem;
padding: 4px;
margin-top: 20px;
border-radius: 12px;
cursor: pointer;
&:hover {
background-color: @color-theme;
color: @color-dark;
}
}
}
}
</style>