1. 程式人生 > >css3 animation 中的 steps

css3 animation 中的 steps

second ima 理解 整數 空心圓 ply settime animation spec

steps

Specifies a stepping function, described above, taking two parameters. The first parameter specifies the number of intervals in the function. It must be a positive integer (greater than 0). The second parameter, which is optional, is either the value ‘start’ or ‘end’, and specifies the point at which the change of values occur within the interval. If the second parameter is omitted, it is given the value ‘end’.

粗略翻譯如下: steps 函數指定了一個階躍函數,第一個參數指定了時間函數中的間隔數量(必須是正整數);第二個參數可選,接受 start 和 end 兩個值,指定在每個間隔的起點或是終點發生階躍變化,默認為 end。

這樣理解起來可能還是有點抽象,我們來個實例:

#demo {
  animation-iteration-count: 2;
  animation-duration: 3s;
}

這是一個 3s * 2 的動畫,我們分別對它應用 steps(3, start)steps(3, end) ,做出階躍函數曲線如下:

1. steps(3, start)

steps() 第一個參數將動畫分割成三段。當指定躍點為 start 時,動畫在每個計時周期的起點發生階躍(即圖中 空心圓 → 實心圓 )。 由於第一次階躍發生在第一個計時周期的起點處(0s),所以我們看到的第一步動畫(初態)就為 1/3 的狀態,因此在視覺上動畫的過程為 1/3 → 2/3 → 1 。如果翻譯成 JavaScript,大致如下:

var animateAtStart = function (steps, duration) {
  var current = 0;
  var interval = duration / steps;
  var timer = function () {
    current++;
    applyStylesAtStep(current);
    if (current < steps) {
      setTimeout(timer, interval);
    }
  };
  timer();
};

2. steps(3, end)

當指定躍點為 end,動畫則在每個計時周期的終點發生階躍(即圖中 空心圓 → 實心圓 )。 由於第一次階躍發生在第一個計時周期結束時(1s),所以我們看到的初態為 0% 的狀態;而在整個動畫周期完成處(3s),雖然發生階躍跳到了 100% 的狀態,但同時動畫結束,所以 100% 的狀態不可視。因此在視覺上動畫的過程為 0 → 1/3 → 2/3 (回憶一下數電裏的異步清零,當所有輸出端都為高電平的時候觸發清零,所以全為高電平是暫態)。同樣翻譯成 JavaScript 如下:

var animateAtEnd = function (steps, duration) {
  var current = 0;
  var interval = duration / steps;
  var timer = function () {
    applyStylesAtStep(current);
    current++;
    if (current < steps) {
      setTimeout(timer, interval);
    }
  };
  timer();
};

css3 animation 中的 steps