實用的 CSS — 貝塞爾曲線(cubic-bezier)

歡迎移步個人博客閱讀:《實用的 CSS — 貝塞爾曲線(cubic-bezier)》css

前言

在瞭解 cubic-bezier 以前,你須要對 CSS3 中的動畫效果有所認識,它是 animation-timing-functiontransition-timing-function 中一個重要的內容。html

本體

簡介

cubic-bezier 又稱三次貝塞爾,主要是爲 animation 生成速度曲線的函數,規定是 cubic-bezier(<x1>, <y1>, <x2>, <y2>)git

咱們能夠從下圖中簡要理解一下 cubic-beziergithub

從上圖咱們須要知道的是 cubic-bezier 的取值範圍:web

  • P0:默認值 (0, 0)瀏覽器

  • P1:動態取值 (x1, y1)函數

  • P2:動態取值 (x2, y2)測試

  • P3:默認值 (1, 1)動畫

咱們須要關注的是 P1 和 P2 兩點的取值,而其中 X 軸的取值範圍是 01,當取值超出範圍時 cubic-bezier 將失效;Y 軸的取值沒有規定,固然也毋須過大。spa

最直接的理解是,將以一條直線放在範圍只有 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 值以及速度曲線

  1. ease:cubic-bezier(.25, .1, .25, 1)

  2. liner:cubic-bezier(0, 0, 1, 1) / cubic-bezier(1, 1, 0, 0)

  3. ease-in:cubic-bezier(.42, 0, 1, 1)

  4. ease-out:cubic-bezier(0, 0, .58, 1)

  5. ease-in-out:cubic-bezier(.42, 0, .58, 1)

  6. In Out . Back(來回的緩衝效果):cubic-bezier(0.68, -0.55, 0.27, 1.55)

效果參考

文章所提到的動畫效果能夠在下面站點中看到,固然你也能夠大膽嘗試:

參考

MDN
W3School

相關文章
相關標籤/搜索