大厂云网站图标动效实现教程

631 阅读2分钟

前言

不少小伙伴发现,现在科技型、工业型的网站,都带有icon动效(鼠标划入的时候会旋转一下),看上去特别炫酷,那么今天就来分享一波,如何实现这种图标动效。

效果

我们先来看几个网站的效果

阿里云

动效阿里.gif

腾讯云

动效腾讯.gif

分析

UI方面

  • 首先要做这种旋转的效果,我们最最最最最重要的不是前端技术,是我们需要得到一张,很长很长的静态图片。这就需要UI去建模一个很长很长很长很长的静态图。我把我们UI切的图贴出来,参考一下。

home-platform.png

有了这张静态长图,下面就是需要展示我们的前端技术来实现效果了。

css3方面

  • 我们前端需要用到的是,CSS3的动画————animation

谈到animation,先了解一下它有哪些属性,分别是什么作用。

  1. animation-duration完成一次所花费的时间(秒或者毫秒,默认0)

  2. animation-timing-function动画的速度曲线,默认值ease

  3. animation-delay动画何时开始,时延

  4. animation-fill-mode动画播放完成后是回到原位置还是停留到目标位置等

  5. animation-iteration-count规定动画播放的次数,默认1

  6. animation-direction规定动画播放完成后是否逆向播放

  7. animation-play-state规定动画是否正在运行或已暂停

  8. animation-iteration-count规定动画播放次数,默认1 简写—— —— animation: 动画名 持续时间 时延 播放次数 是否轮流反向播放 ;

  • 将图片作为背景图,利用背景图的 background-position 属性去移动它的Y轴位置。

JS方面

  • 用vue的 @mouseover@mouseleave 两个属性分别去进行一个加类和去类的JS操作

代码

<template>
  <div class="wrapper">
    <ul class="wrapper-bar">
      <li
        v-for="(item, ind) in classify"
        :key="ind"
        :style="{
          backgroundImage: 'url(' + item.svg + ')',
        }"
        class="tab-img"
        :class="mouseActive === ind ? mouseStyle : 'is-leave'"
        @mouseover="handleImgOver(ind)"
        @mouseleave="handleImgOut(ind)"
      ></li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      mouseStyle: '',
      mouseActive: 0,
      classify: [
        {
          title: '生产制造',
          svg: require('../assets/home-production.png'),
        },
        {
          title: '研发设计',
          svg: require('../assets/home-design.png'),
        },
        {
          title: '数据服务',
          svg: require('../assets/home-data.png'),
        },
        {
          title: '平台服务',
          svg: require('../assets/home-platform.png'),
        },
      ],
    };
  },
  methods: {
    handleImgOver(i) {
      this.mouseStyle = 'is-entery';
      this.mouseActive = i;
    },
    handleImgOut(i) {
      this.mouseStyle = 'is-leave';
      this.mouseActive = i;
    },
  },
};
</script>

<style scoped>
.wrapper {
  width: 100%;
}
.wrapper-bar {
  width: 100%;
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: space-evenly;
  cursor: pointer;
}
.tab-img {
  width: 80px;
  height: 80px;
  overflow: hidden;
  background-repeat: no-repeat;
  background-size: 100% auto;
}

.is-entery {
  animation: entery 0.4s steps(15) forwards;
}
.is-leave {
  animation: leave 0.4s steps(15) forwards;
}
@keyframes entery {
  0% {
    background-position: 0 0;
  }
  to {
    background-position: 0 -1200px;
  }
}
@keyframes leave {
  0% {
    background-position: 0 -1200px;
  }

  100% {
    background-position: 0 0;
  }
}
</style>

计算

这块需要我们做一个计算(也是重点),就是animation:steps()和background-position: 0 ;。

  1. 数一下图片的帧数(图片个数)
  2. 自己设计好图片的大小(width X height)
  3. steps的值就是图片帧数-1
  4. position的值就是图片的高*steps

demo演示

demo动效.gif

总结

其实效果不是很难,多动脑,多总结。