我們經(jīng)常使用css3中的animation動(dòng)畫玉吁,比如這樣:
.fadeIn{
animation: fadeIn .5s ease 1s both;
}
@keyframes fadeIn{
from{
opacity:0;
}
to{
opacity:1
}
}
這樣就實(shí)現(xiàn)了延時(shí)1s,一共0.5s的淡入動(dòng)畫场斑。其中ease是animation-timing-function的默認(rèn)值刻两。
animation-timing-function使用了三次貝塞爾(Cubic Bezier)函數(shù)生成速度曲線,可以讓我們的動(dòng)畫產(chǎn)生平滑的過(guò)渡杆逗。
但是有的時(shí)候我們并不想要平滑的過(guò)渡,比如想要實(shí)現(xiàn)下面小人跑動(dòng)的效果鳞疲,該怎么實(shí)現(xiàn)呢罪郊?
小人跑動(dòng)動(dòng)畫
-
我們可以將小人跑動(dòng)的動(dòng)作分解,拼成下面的雪碧圖:
小人動(dòng)作分解 - 通過(guò)設(shè)置不同的background-position設(shè)置不同時(shí)間小人不通的動(dòng)作
@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讓動(dòng)畫動(dòng)起來(lái)吧尚洽,想讓動(dòng)畫每幀動(dòng)悔橄,而不帶中間的過(guò)渡效果animation-timing-function要設(shè)置成steps函數(shù)
.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;
}
小人跑動(dòng)動(dòng)畫
- 小人動(dòng)起來(lái)啦!
或者更簡(jiǎn)單腺毫,把雪碧圖拼成這樣:
小人動(dòng)作分解.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函數(shù)接受兩個(gè)參數(shù)癣疟,第一個(gè)參數(shù)會(huì)根據(jù)你指定的步進(jìn)數(shù)量,把整個(gè)動(dòng)畫切分為多幀潮酒,第二個(gè)可選的參數(shù)可以是 start 或 end(默認(rèn))睛挚。這個(gè)參數(shù)用于指定動(dòng)畫在每個(gè)循環(huán)周期的什么位置發(fā)生幀的切換動(dòng)作。還可以使用 step-start 和 step-end 這樣的簡(jiǎn)寫屬性,它們分別等同于 steps(1, start) 和 steps(1, end)
很多時(shí)候我們的gif動(dòng)畫都可以直接用css效果實(shí)現(xiàn)急黎,快來(lái)試試吧竞川!