這是〈Svelte 從小白到入門〉系列的第七集,各集連結如下:


Tweening

當某個值變動要反映在畫面上時,Svelte 提供了 tweening 工具讓元件在畫面上的過渡過程是平滑的。

所謂的「tweening」指的是一個物件從 A 狀態變化成 B 狀態時,中間的那些過渡過程,藉由 Svelte 提供的 tweened 函式,可以協助我們產生那些過渡,畢竟不可能由人工去定義每一瞬間的狀態。

在下面的例子裡,按鈕會改變進度條的狀態(數值),在沒有 tweening 以前,就是很直接的從 0% 切換到 100%,加上 tweening 效果後,進度條從 0% 到 100% 的過程就會是平滑過渡的:

在把玩時,還可以注意到,在進度條跑到中間時,又按下 0% 的按鈕,此時跑到一半的進度條會開始倒退走,而不是傻傻的跑到底才倒退走,這些 UX 上的細節 Svelte 都已經幫我們顧慮到了,揪感心~

在程式碼的部份,我們用 tweened() 函式建構一個 tweening 物件 progress,它的設值方法和上一集的 store 如出一轍都是 set(),就不著墨太多。

tweened() 函式本身接受兩個參數,第一個參數是 progress 的初值,第二個參數是它的一些細部配置,這裡我們指定了 tweening 過渡的時長為 4,000 ms,而 easing 模式為 cubicOut

tweened() 的配置參數如下(太深奧了不解釋):

  • delay — milliseconds before the tween starts
  • duration — either the duration of the tween in milliseconds, or a (from, to) => milliseconds function allowing you to (e.g.) specify longer tweens for larger changes in value
  • easing — a p => t function
  • interpolate — a custom (from, to) => t => value function for interpolating between arbitrary values. By default, Svelte will interpolate between numbers, dates, and identically-shaped arrays and objects (as long as they only contain numbers and dates or other valid arrays and objects). If you want to interpolate (for example) colour strings or transformation matrices, supply a custom interpolator

Q 彈效果

還有一個函式是 spring(),顧名思義就是做出像彈簧般 Q 彈的效果,除了配置參數不同外,用起來和 tweened() 大同小異。

spring() 的配置參數有:

  • stiffness:剛性係數
  • damping:阻尼係數

他們的作用可以透過實例感受,在下面的例子裡,我們設定 spring() 的初值為 { x: 50, y: 50 } 的座標點,並將此座標設為變數 coords 綁定到小黑點上,小黑球的移動則是靠一系列的 on: 綁定滑鼠事件與匿名函式,一旦滑鼠從 A 點移動到 B 點,則 spring() 會幫我們計算小黑球在兩點中間的 Q 彈行為:

小結

tweened()spring() 都有著與 store 相同的 set()update() 方法,實際上,tweened()spring() 就是上一集介紹過的 custom store,是 Svelte 感心的為用戶預先準備好的工具,真的是揪感心耶!

本集重點整理:

  • Tweening 指的是起末兩狀態間的過渡狀態,Svelte 提供了 tweened() 幫我們處理掉 tweening 的工作
  • Tweening 中間的過渡模式稱為 easing,有許多業界既有的 easing 模式可選用
  • spring() 一樣是處理過渡狀態,並且是產生 Q 彈的彈簧效果,喜歡 Q 彈的人不能錯過
  • tweened()spring() 也都是 store,再加上被賦予的額外特性