序列图动画效果实现

166 阅读1分钟
又入职一家新公司,帮人家重构官网,其中有一个动画效果是用 png 序列图实现的,这种效果见过,但要我实现我却不会,左找右找也没找到类似的文章,于是琢磨了一下,稍有了解,于是写下这篇文章希望帮到有需要的人。

首先看效果,如下图

018c6b61ee0fcd11013f01cdc9e025.jpg

话不多说,直接上代码

<template>
  <div class="imgBox" @mouseleave="handleMouseleave" @mouseenter="handleMouseenter" >
    <div class="img" ref="img" >
      <img src="https://cdn.cxka.com/images/web/static/liaotianxitong.png" />
    </div>
  </div>
</template> 

<script setup>
const img = ref()

const handleMouseenter = () => {
  let t = 21;            // 图片有21帧
  let a = 1449 / t;      // 图片长度除以帧数
  for (let index = 0; index < t; index++) {
    setTimeout(() => {
      img.value.style.marginLeft = -a * index + "px";
    }, t * index);
  }
};

const handleMouseleave = () => {
  let t = 21;
  let a = 1449 / t;
  for (let index = 20; index >= 0; index--) {
    setTimeout(() => {
      img.value.style.marginLeft = -a * index + "px";
    }, (t - index) * t);
  }
};
</script>

<style>
.imgBox {
  width: 66px;
  height: 66px;
  overflow: hidden;
  cursor: pointer;
 }
 
 .img {
   width: 1449px;
   height: 66px;
 }
 
 img {
   width: 100%;
   height: 100%;
 }
</style>

这样就实现 png 序列图的动画效果了