使用CSS做貝茲路徑

來源:互聯網
上載者:User

前言

在瞭解 cubic-bezier 之前,你需要對 CSS3 中的動畫效果有所認識,它是 animation-timing-functiontransition-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 軸的取值範圍是 01,當取值超出範圍時 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>  <p class="animation"></p></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)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)
相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.