1. 程式人生 > 其它 >css逐幀動畫

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>