最近突发奇想弄个主页,去找了个开源的项目,又看上了个酷炫的背景想换一下,主页用的是 vite+vue3 纯静态无路由的一个页面,里面有几个组件,其中有一个就是背景的组件 Background.vue,下面的 FluidBackground.vue 是我建的。
打算换成[PavelDoGreat/WebGL-Fluid-Simulation: Play with fluids in your browser (works even on mobile) (github.com)] 这个背景,看着换起来挺简单,就是 template 里一个 canvas 再引入一个 js 就好了,因为加载顺序的问题,经过一番努力还是没解决
<template>
<div :class="store.backgroundShow ? 'cover show' : 'cover'">
<canvas
id="background"
v-show="store.imgLoadStatus"
class="bg"
@load="imgLoadComplete"
@animationend="imgAnimationEnd" />
</div>
</template>
<script setup>
console.log("vue script开始加载");
import { mainStore } from "@/store";
import {onMounted} from "vue";
// import "@/utils/script.js";
import {resizeCanvas, setCanvas} from "@/utils/script2.js";
const store = mainStore();
const imgTimeout = ref(null);
const emit = defineEmits(["loadComplete"]);
onMounted(()=>{
nextTick(()=>{
console.log("onMounted");
const canvas = document.getElementById('background');
setCanvas(canvas);
resizeCanvas();
})})
const imgAnimationEnd = () => {
console.log("壁纸加载且动画完成");
// 加载完成事件
emit("loadComplete");
};
// 图片加载完成
const imgLoadComplete = () => {
imgTimeout.value = setTimeout(
() => {
store.setImgLoadStatus(true);
},
Math.floor(Math.random() * (600 - 300 + 1)) + 300,
);
console.log("图片加载完成");
};
onBeforeUnmount(() => {
clearTimeout(imgTimeout.value);
console.log("onBeforeUnmount");
})
</script>
<style scoped lang="scss">
.cover {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
transition: 0.25s;
z-index: -1;
&.show {
z-index: 1;
}
.bg {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
object-fit: cover;
backface-visibility: hidden;
filter: blur(20px) brightness(0.3);
transition:
filter 0.3s,
transform 0.3s;
animation: fade-blur-in 0.8s cubic-bezier(0.25, 0.46, 0.45, 0.94) forwards;
animation-delay: 0.45s;
}
}
</style>
我理解的是,每次页面加载 js 比渲染 dom 元素早,所以导致读取不到元素的属性,不知道是不是这样,请教下大家有什么解决办法吗,可以加我微信 GL735029665,请杯咖啡作为感谢