歡迎移步我的博客閱讀:《實用的 CSS — 貝塞爾曲線(cubic-bezier)》
前言
在了解 cubic-bezier
之前,你需要對 CSS3 中的動畫效果有所認識,它是 animation-timing-function
和 transition-timing-function
中一個重要的內容。
本體
簡介
cubic-bezier
又稱三次貝塞爾,主要是為 animation
生成速度曲線的函數,規定是 cubic-bezier(<x1>, <y1>, <x2>, <y2>)
。
我們可以從下圖中簡要理解一下 cubic-bezier
:
從上圖我們需要知道的是 cubic-bezier
的取值范圍:
- P0:默認值 (0, 0)
- P1:動態取值 (x1, y1)
- P2:動態取值 (x2, y2)
- P3:默認值 (1, 1)
我們需要關注的是 P1 和 P2 兩點的取值,而其中 X 軸
的取值范圍是 0 到 1,當取值超出范圍時 cubic-bezier
將失效;Y 軸
的取值沒有規定,當然也毋須過大。
最直接的理解是,將以一條直線放在范圍只有 1 的坐標軸中,并從中間拿出兩個點來拉扯(X 軸的取值區間是 [0, 1],Y 軸任意),最后形成的曲線就是動畫的速度曲線。
使用
在測試例子中:
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.animation {
width: 50px;
height: 50px;
background-color: #ed3;
-webkit-transition: all 2s;
-o-transition: all 2s;
transition: all 2s;
}
.animation:hover {
-webkit-transform: translateX(100px);
-ms-transform: translateX(100px);
-o-transform: translateX(100px);
transform: translateX(100px);
}
</style>
</head>
<body>
<div class="animation"></div>
</body>
</html>
我們可以在瀏覽器中看到,當鼠標移到元素上時,元素開始向右移動,開始比較慢,之后則比較快,移開時按原曲線回到原點。
在例子中,當我們不為 transition
添加 cubic-bezier
或是其他 timing-function
時,默認的速度曲線是 ease
,此時的速度曲線是:
那么讓我們在代碼中加入 cubic-bezier(.17, .86, .73, .14)
:
...
.animation {
...
-webkit-transition: all 2s cubic-bezier(.17, .86, .73, .14);
-o-transition: all 2s cubic-bezier(.17, .86, .73, .14);
transition: all 2s cubic-bezier(.17, .86, .73, .14);
}
...
再刷新頁面觀察效果,會看到動畫在執行過程中有一段很緩慢的移動,前后的速度相似,此時的運動曲線是:
幾個常用的固定值對應的 cubic-bezier
值以及速度曲線
-
ease
:cubic-bezier(.25, .1, .25, 1)
-
liner
:cubic-bezier(0, 0, 1, 1) / cubic-bezier(1, 1, 0, 0)
-
ease-in
:cubic-bezier(.42, 0, 1, 1)
-
ease-out
:cubic-bezier(0, 0, .58, 1)
-
ease-in-out
:cubic-bezier(.42, 0, .58, 1)
-
In Out . Back(來回的緩沖效果):cubic-bezier(0.68, -0.55, 0.27, 1.55)
效果參考
文章所提到的動畫效果可以在下面站點中看到,當然你也可以大膽嘗試: