.monster { width: 190px; height: 240px; margin: 2% auto; background: url('http://treehouse-code-samples.s3.amazonaws.com/CSS-DD/codepen/blog/monster.png') left center; animation: play .8s steps(10) infinite; } @keyframes play { 100% { background-position: -1900px; } }
有一個在CSS動畫一個鮮為人知的定時功能,可以讓我們打破一個動畫成段 - 或步驟 - 而不是運行它作為一個連續的動畫從開始到結束。因為我們能夠精確顯示每個精靈形象作為一個框架,沒有任何緩和效果插圖中,此功能是用於創建精靈表的動畫非常有用。
steps()函數
steps(),我們能夠控制關鍵幀動畫的時間呈現的數量;它發展的基礎上,我們設置的值等距離步驟動畫。知道了這一點,讓我們使用steps()來創建一個簡單的人物精靈表的動畫。
我的Illustrator畫板來創建每個動畫幀作為一個獨立的190×240的圖像,然后把北斗“spriting功能優勢,以快速生成包含所有導出的圖像水平精靈表。
Creating the animation
To animate our monster character, we’ll first create a rule where we define the width and height dimensions and display the main sprite sheet as a background image.
.monster { width: 190px; height: 240px; background: url('monster-sprite.png') left center; }
Next, we need to create a keyframe rule that animates the background position of the sprite sheet. The sprite sheet’s total width is 1900px, so let’s animate it right-to-left by giving it a final background position of -1900px.
@keyframes play { 100% { background-position: -1900px; } }
Running the animation
At this point, when we bind the play
animation sequence to the .monster
selector with a duration of .8s, we see the background position of our sprite sheet quickly animating from left to right.
.monster { ... animation: play .8s; }
To achieve the desired frame-by-frame animation effect, we’ll need to include the steps()
timing function in the animation
value. Since the sprite sheet contains 10 image sprites, we can say that it’s made up of 10 frames––or steps. So let’s define 10 steps in our animation sequence:
.monster { ... animation: play .8s steps(10); }
So now, the animation will run 10 frames in its .8s duration – it uses the background position animation to run through each sprite image as a step.
Finally, if we set animation-iteration-count
to infinite
, it will render a repeating loop of the animation.
.monster { ... animation: play .8s steps(10) infinite; }