使用 SMIL 的 SVG 動畫

同步多媒體整合語言 (SMIL) 是一種基於 XML 的語言,用於編寫互動式多媒體簡報。作者可以在其他基於 XML 的語言中使用 SMIL 語法來定義動畫元素的計時和佈局。

SMIL 允許您

以下各節將展示如何在 SVG 中將 SMIL 用於這四種用例。

為元素的屬性設定動畫

以下示例為圓的 cx 屬性設定動畫。為此,我們在 <circle> 元素內添加了一個 <animate> 元素。對於 <animate> 來說,重要的屬性是

屬性名稱

要設定動畫的屬性的名稱。

from

屬性的初始值。

改為

最終值。

持續時間

動畫的時長 (例如,寫 '5s' 表示 5 秒)。

如果您想在同一個元素內為更多屬性設定動畫,可以新增更多的 <animate> 元素。

html
<svg width="300" height="100">
  <title>Attribute Animation with SMIL</title>
  <rect x="0" y="0" width="300" height="100" stroke="black" stroke-width="1" />
  <circle cx="0" cy="50" r="15" fill="blue" stroke="black" stroke-width="1">
    <animate
      attributeName="cx"
      from="0"
      to="500"
      dur="5s"
      repeatCount="indefinite" />
  </circle>
</svg>

為 transform 屬性設定動畫

<animateTransform> 元素允許您為 transform 屬性設定動畫。此元素是必需的,因為我們不是在為像 x 這樣的單個數值屬性設定動畫。旋轉屬性看起來像這樣:rotation(theta, x, y),其中 theta 是以度為單位的角度,xy 是絕對位置。在下面的示例中,我們為旋轉中心和角度設定了動畫。

html
<svg width="300" height="100">
  <title>SVG SMIL Animate with transform</title>
  <rect x="0" y="0" width="300" height="100" stroke="black" stroke-width="1" />
  <rect
    x="0"
    y="50"
    width="15"
    height="34"
    fill="blue"
    stroke="black"
    stroke-width="1">
    <animateTransform
      attributeName="transform"
      begin="0s"
      dur="20s"
      type="rotate"
      from="0 60 60"
      to="360 100 60"
      repeatCount="indefinite" />
  </rect>
</svg>

跟隨路徑的動畫

<animateMotion> 元素允許您根據路徑來為元素的位移和旋轉設定動畫。路徑的定義方式與 <path> 相同。您可以設定屬性來定義物件是否會沿著路徑的切線方向旋轉。

示例 1:直線運動

在此示例中,一個藍色圓圈在一個黑色框的左右邊緣之間來回彈跳,無限迴圈。這裡的動畫由 <animateMotion> 元素處理。在這種情況下,我們建立了一個路徑,該路徑由一個 MoveTo 命令定義動畫的起點,然後是 Horizontal-line 命令將圓向右移動 300 畫素,接著是 Z command,它會閉合路徑,建立一個回到起點的迴圈。透過將 repeatCount 屬性的值設定為 indefinite,我們指示動畫應該永遠迴圈,只要 SVG 影像存在。

html
<svg xmlns="http://www.w3.org/2000/svg" width="300" height="100">
  <title>SVG SMIL Animate with Path</title>
  <rect x="0" y="0" width="300" height="100" stroke="black" stroke-width="1" />
  <circle cx="0" cy="50" r="15" fill="blue" stroke="black" stroke-width="1">
    <animateMotion path="M 0 0 H 300 Z" dur="3s" repeatCount="indefinite" />
  </circle>
</svg>

檢視即時示例

示例 2:曲線運動

與上一個示例相同,但使用曲線路徑並跟隨路徑方向。

html
<svg width="300" height="100">
  <title>SVG SMIL Animate with Path</title>
  <rect x="0" y="0" width="300" height="100" stroke="black" stroke-width="1" />
  <rect
    x="0"
    y="0"
    width="20"
    height="20"
    fill="blue"
    stroke="black"
    stroke-width="1">
    <animateMotion
      path="M 250,80 H 50 Q 30,80 30,50 Q 30,20 50,20 H 250 Q 280,20,280,50 Q 280,80,250,80Z"
      dur="3s"
      repeatCount="indefinite"
      rotate="auto" />
  </rect>
</svg>

另見