particles.js github地址 居然有20.5k厉害了;
一开始通过npm下载,但是其插件不支持 import模块化,就直接把js下载下来吧(min的23kb),少一个npm包文件
组件内引入
import '@/utils/lib/particles.min.js'
初始化,传入div的id和配置
particlesJS('particles', config);
配置参考了这个 JS库之Particles.js中文开发手册及参数详解
遇到的问题
1.页面高度变化,但是其不会更新,直接拉伸画布,且该插件没有暴露更新的方法,又发现它会检测resize时更新,故在点击展开列表等影响页面高度变化的操作后,手动触发window 的resize事件
window.dispatchEvent( new Event('resize'));
2.切换页面的时候,不同页面高度不同,粒子画布会拉伸,此时是路由切换没有触发上面的事件,觉得引发页面高度变化的操作有很多,故想要直接监听dom的高度变化,然后更新画布,找到如下
- html5 mutation observer 不能监听元素尺寸变化,还有何用? - justjavac的回答 - 知乎
- 其上提到的插件ResizeObserver Polyfill;亲测有效,看了下包里面ResizeObserver.js是37kb,压缩后7.7kb
- 之前还看到用定时器的,太low,上面那个是用MutationsObserver 和DOMSubtreeModified 来实现
下面为封装为vue组件的代码
<!-- 粒子效果组件 -->
<template>
<transition name="fade2">
<div
class="VParticles"
v-show="isShow"
>
<div id="particles"></div>
</div>
</transition>
</template>
<script>
import ResizeObserver from 'resize-observer-polyfill';
import EventBus from '@/utils/eventBus';
import '@/utils/lib/particles.min.js';
import particlesConfig from './particles.json';
export default {
name: '',
components: {
},
props: {
},
data() {
return {
isShow: true,
};
},
computed: {
},
created() {
},
mounted() {
this.init();
this.change();
},
methods: {
init(config = particlesConfig) {
// eslint-disable-next-line no-undef
particlesJS('particles', config);
},
change() {
EventBus.$on('changeMine', (tableItem) => {
if (this.$route.path != '/finance') { return; }
this.isShow = false;
const newConfig = this.$common.cloneDeep(particlesConfig);
if (tableItem) {
newConfig.particles.shape.image.src = tableItem.icon;
newConfig.particles.shape.type = 'image';
// 延时显示,是因为粒子画布在变化的时候会抖动拉扯
}
setTimeout(() => {
this.init(newConfig);
this.isShow = true;
}, 300);
});
// 防抖一下
const resize = this.$common.debounce(() => {
window.dispatchEvent(new Event('resize'));
}, 500);
// 监听粒子画布的高度变化,变化后都要重新更新一次,否则会画布会拉伸
const ro = new ResizeObserver((entries, observer) => {
// 触发resize,让particles更新视图
// 由于该插件没有暴露更新的方法,又发现它会检测resize,故这么做
resize();
});
ro.observe(document.getElementById('particles'));
},
},
};
</script>
<style lang='less' scoped>
#particles {
position: absolute;
top: 0;
left: 0;
z-index: 100;
width: 100%;
height: 100%;
background-color: #f6f9fc;
background-repeat: no-repeat;
background-size: cover;
background-position: 50% 50%;
}
.fade2-enter-active {
transition: opacity 0.5s;
}
.fade2-enter {
opacity: 0;
}
</style>
网友评论