動畫

Konva.Animation

要在 Konva 中製作動畫,可使用 Konva.Animation 建構子,同時必須提供以下兩個參數:

  • 用來更新畫格 (frame) 的函式
  • 選擇的圖層或圖層陣列 (可選參數)

在動畫的每次畫格中,都會呼叫更新畫格的函式,其中會傳入一個 frame 參數,包含有以下 3 個屬性:

  • time 屬性:動畫開始到目前畫格的毫秒數
  • timeDiff 屬性:從上次最後的畫格到目前畫格的毫秒數
  • frameRate 屬性:目前每秒的畫格率 (frames per second)

HTML5 Canvas + Konva 動畫的使用樣板:

更新畫格的函式應包含更新圖形屬性的邏輯,例如圖形的位置、旋轉、縮放、寬度、高度、半徑、顏色等。

動畫建構好之後,可以隨時呼叫 start() 函式啟動動畫。

移動

以下範例,我們要做出一顆紅球水平來回移動。

HTML 部份

插入 Konva JS 代碼,同時準備一個元素設定其 id,以供 Konva 繪圖使用。

<script src="https://unpkg.com/konva@3.4.1/konva.min.js"></script>
<div id="container"></div>
1
2

JS 部份

使用 Shape.move({x:dx, y:dy}) 函式移動紅球,此處 (dx, dy) 為位移向量。

var stage = new Konva.Stage( { // Create a stage
  container: 'container', width: 500, height: 100
});
var layer = new Konva.Layer(); // Create a layer

var circle = new Konva.Circle({ // Create the red ball
  x:30, y:50, radius:10, fill:'red'
});

layer.add(circle); // Add the ball to the layer
stage.add(layer);  // Add the layer to the stage

var speed = 0.2; // ball speed: pixels per ms
var anim = new Konva.Animation(function(frame)
{
  // timeDiff * speed = move distance
  circle.move({x: frame.timeDiff*speed, y:0});
  // if move to boundary, then change the speed sign
  if (circle.x()>470 || circle.x()<30) {
  	speed = -speed;
  }
}, layer);

anim.start() // start the animation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

結果

如果畫面中沒有出現紅球的話,按一下 HTML/JavaScript 頁面,然後再按回 Result 頁面,應該就會出現。

旋轉

使用 Shape.rotation(angle) 函式來設定形狀的旋轉角度 (angle)。以矩形來說,預設的旋轉中心點為矩形左上角的位置,但是可以使用 offset 屬性事先平移矩形的位置,然後再以原來的中心點進行旋轉。不論有無平移,最後旋轉的中心點為矩形的 x 屬性和 y 屬性所構成的座標點。



練習

試著設計出以下的動畫。