使用 SMIL 的 SVG 動畫
同步多媒體整合語言 (SMIL) 是一種基於 XML 的語言,用於編寫互動式多媒體簡報。作者可以在其他基於 XML 的語言中使用 SMIL 語法來定義動畫元素的時間和佈局。SMIL 允許您
以下部分展示瞭如何在 SVG 中使用 SMIL 來實現這四種用例。
動畫元素的屬性
以下示例動畫了圓形的 cx 屬性。為此,我們在 <circle> 元素內部添加了一個 <animate> 元素。對於 <animate>,重要的屬性有:
attributeName-
要動畫化的屬性的名稱。
from-
屬性的初始值。
to-
最終值。
dur-
動畫的持續時間(例如,5 秒寫成 '5s')。
如果要在一個元素內動畫化多個屬性,可以新增多個 <animate> 元素。
<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>
動畫變換屬性
<animateTransform> 元素允許您動畫化 transform 屬性。需要使用此元素,因為我們沒有動畫化像 x 這樣的單個數字屬性。旋轉屬性如下所示:rotation(theta, x, y),其中 theta 是以度為單位的角度,x 和 y 是絕對位置。在下面的示例中,我們動畫化了旋轉中心和角度。
<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 命令**,它關閉了路徑,建立了一個返回起點的迴圈。透過將 **repeatCount** 屬性的值設定為 indefinite,我們指示動畫應該無限迴圈,只要 SVG 影像存在。
<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:曲線運動
與之前的示例相同,但使用曲線路徑並跟隨路徑方向。
<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>