web前端首页投稿(暂停使用,暂停投稿)程序员

css逐帧动画

2016-08-07  本文已影响1131人  xy香油酱

我们经常使用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)函数生成速度曲线,可以让我们的动画产生平滑的过渡。
但是有的时候我们并不想要平滑的过渡,比如想要实现下面小人跑动的效果,该怎么实现呢?

小人跑动动画
@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
  }
}
.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;
}
小人跑动动画

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

小人动作分解.png
.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效果实现,快来试试吧!

上一篇 下一篇

猜你喜欢

热点阅读