vue 图片流光特效

1,前端需要标题背景显示流光的特效,

解决方案是根据时间周期动态切换显示图片,营造出流光的特效。

图片路径 src/assets/title-imgs,文件如图显示:


目录

title_00000.png

title_00001.png

title_00002.png

title_00003.png

title_00004.png

完整文件如下:

<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>
  
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容