1,前端需要标题背景显示流光的特效,
解决方案是根据时间周期动态切换显示图片,营造出流光的特效。
图片路径 src/assets/title-imgs,文件如图显示:
完整文件如下:
<template>
<div class="chart-container">
<img
class="title-bg"
v-for="(png, i) in pngList"
:key="i"
v-show="i === currentPngIndex"
:src="png"
alt=""
/>
<div class="title-text">{{ parsedText }}</div>
</div>
</template>
<script setup lang="ts">
import { ref, onBeforeUnmount, onMounted } from 'vue'
// 可以用props 传入
const parsedText = ref('标题')
// 图片集合
const pngList = ref<string[]>([])
// 图片序号
const currentPngIndex = ref(-1)
const carouselTimeoutId = ref<any>(null)
// 流动图片总数
const maxImgLength = ref(5)
onMounted(() => {
showNextPng()
})
onBeforeUnmount(() => {
clearTimeout(carouselTimeoutId.value)
})
const getImgUrl = (name: string) => {
// 当前图片路径
return new URL('../assets/title-imgs/' + name, import.meta.url).href
}
initImg()
// 动态设置所有图片路径
function initImg() {
for (let i = 0; i < maxImgLength.value; i++) {
let suffix = ('00000' + i).slice(-5)
let titleBg = getImgUrl(`title_${suffix}.png`)
pngList.value.push(titleBg)
}
}
function showNextPng() {
let nextPngIndex = currentPngIndex.value + 1
if (nextPngIndex >= pngList.value.length) {
nextPngIndex = 0
}
currentPngIndex.value = nextPngIndex
carouselTimeoutId.value = setTimeout(showNextPng, 180)
}
</script>
<style scoped>
.chart-container {
width: 100%;
height: 80px;
position: relative;
.title-bg {
width: 100%;
height: 100%;
position: absolute;
}
.title-text {
position: absolute;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
margin-top: 16px;
color: #fff;
font-weight: 700;
font-size: 34px;
letter-spacing: 4px;
}
}
</style>