css逐帧动画

我们经常使用css3中的animation动画,比如这样:

.fadeIn{
  animation: fadeIn .5s ease 1s both;
}
@keyframes fadeIn{
  from{
    opacity:0;
  }
  to{
    opacity:1
  }
}

这样就实现了延时1s,一共0.5s的淡入动画。其中ease是animation-timing-function的默认值。
animation-timing-function使用了三次贝塞尔(Cubic Bezier)函数生成速度曲线,可以让我们的动画产生平滑的过渡。
但是有的时候我们并不想要平滑的过渡,比如想要实现下面小人跑动的效果,该怎么实现呢?

  • 我们可以将小人跑动的动作分解,拼成下面的雪碧图:

    • 通过设置不同的background-position设置不同时间小人不同的动作
    @keyframes run {
      0% {
        background-position: 0 0
      }
      10%{
        background-position: -100% 0
      }
      20%{
        background-position: -200% 0
      }
      30%{
        background-position: -300% 0
      }
      40%{
        background-position: -400% 0
      }
      50%{
        background-position: 0 -100%
      }
      60%{
        background-position: -100% -100%
      }
      70%{
        background-position: -200% -100%
      }
      80%{
        background-position: -300% -100%
      }
      90%{
        background-position: -400% -100%
      }
      100%{
        background-position: 0 0
      }
    }
    • 用animation让动画动起来吧,想让动画每帧动,而不带中间的过渡效果animation-timing-function要设置成steps函数
    .people{
        width: 100px;
        height: 114px;
        background: url(../images/people.png);
        -webkit-animation:run 1s steps(1) 0s infinite both;
        animation:run 1s steps(1) 0s infinite both;
    }


  • 小人动起来啦!

或者更简单,把雪碧图拼成这样:

.people{
    width: 100px;
    height: 114px;
    background: url(../images/people.png);
    -webkit-animation:run 1s steps(9) 0s infinite both;
    animation:run 1s steps(9) 0s infinite both;
}

@-webkit-keyframes run {
  to{
    background-position: -900% 0
  }
}

steps函数接受两个参数,第一个参数会根据你指定的步进数量,把整个动画切分为多帧,第二个可选的参数可以是 start 或 end(默认)。这个参数用于指定动画在每个循环周期的什么位置发生帧的切换动作。还可以使用 step-start 和 step-end 这样的简写属性,它们分别等同于 steps(1, start) 和 steps(1, end)
很多时候我们的gif动画都可以直接用css效果实现,快来试试吧!

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .people {
            width: 110px;
            height: 114px;
            overflow: hidden;
        }

        .people img {
            height: 114px;
            animation: move 1s steps(9) 0s infinite both ;
        }

        @keyframes move {
            from {
                transform: translateX(0);
            }
            to {
                transform: translateX(-913px);
            }
        }
    </style>
</head>
<body>
<div class="people">
    <img src="img_1.png" alt="">
</div>
</body>
</html>

posted @ 2022-06-06 10:52  木子欢儿  阅读(195)  评论(0编辑  收藏  举报