SVG 動畫
SVG 動畫
SVG 元素可以動畫化。
在 SVG 中,我們有四個動畫元素來設定或動畫化 SVG 圖形
-
<set>
-
<animate>
-
<animateTransform>
-
<animateMotion>
SVG <set>
<set>
元素用於在指定持續時間內設定屬性的值。
在此示例中,我們建立一個紅色圓圈,其半徑初始為 25,3 秒後半徑將設定為 50
這是 SVG 程式碼
示例
<svg width="200" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="50" cy="50" r="25" style="fill:red;">
<set attributeName="r" to="50" begin="3s" />
</svg>
自己動手試一試 »
程式碼解釋
<set>
元素中的attributeName
屬性定義要更改的屬性<set>
元素中的to
屬性定義屬性的新值<set>
元素中的begin
屬性定義動畫何時開始
SVG <animate>
<animate>
元素用於動畫化元素的屬性。
<animate>
元素應巢狀在目標元素內。
在此示例中,我們建立一個紅色圓圈。我們動畫化 cx 屬性從 50 到 90%。這意味著圓圈將從左向右移動
這是 SVG 程式碼
示例
<svg width="100%" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="50" cy="50" r="50" style="fill:red;">
<animate
attributeName="cx"
begin="0s"
dur="8s"
from="50"
to="90%"
repeatCount="indefinite" />
</circle>
</svg>
自己動手試一試 »
程式碼解釋
attributeName
屬性定義要動畫化的屬性begin
屬性定義動畫何時開始dur
屬性定義動畫的持續時間from
屬性定義起始值to
屬性定義結束值repeatCount
屬性定義動畫播放的次數
帶凍結的 SVG <animate>
在此示例中,我們希望紅色圓圈在到達最終位置時凍結(停止)(而不是彈回起始位置)
這是 SVG 程式碼
示例
<svg width="100%" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="50" cy="50" r="50" style="fill:red;">
<animate
attributeName="cx"
begin="0s"
dur="8s"
from="50"
to="90%"
fill="freeze" />
</circle>
</svg>
自己動手試一試 »
程式碼解釋
fill="freeze"
屬性定義動畫在到達最終位置時應凍結
SVG <animateTransform>
<animateTransform>
元素用於動畫化目標元素的 transform
屬性。
<animateTransform>
元素應巢狀在目標元素內。
在此示例中,我們建立一個將旋轉的紅色矩形
這是 SVG 程式碼
示例
<svg width="200" height="180" xmlns="http://www.w3.org/2000/svg">
<rect x="30" y="30" height="110" width="110" style="stroke:green;fill:red">
<animateTransform
attributeName="transform"
begin="0s"
dur="10s"
type="rotate"
from="0 85 85"
to="360 85 85"
repeatCount="indefinite" />
</rect>
</svg>
自己動手試一試 »
程式碼解釋
attributeName
屬性動畫化<rect>
元素的transform
屬性begin
屬性定義動畫何時開始dur
屬性定義動畫的持續時間type
屬性定義變換的型別from
屬性定義起始值to
屬性定義結束值repeatCount
屬性定義動畫播放的次數
SVG <animateMotion>
<animateMotion>
元素設定元素沿運動路徑的移動方式。
<animateMotion>
元素應巢狀在目標元素內。
在此示例中,我們建立一個矩形和一段文字。這兩個元素都具有相同的路徑 <animateMotion>
元素
這是 SVG 程式碼
示例
<svg width="100%" height="150" xmlns="http://www.w3.org/2000/svg">
<rect x="45" y="18" width="155" height="45" style="stroke:green;fill:none;">
<animateMotion
path="M0,0 q60,100 100,0 q60,-20 100,0"
begin="0s"
dur="10s"
repeatCount="indefinite" />
</rect>
<text x="50" y="50" style="font-family:Verdana;font-size:32">它是 SVG!
<animateMotion
path="M0,0 q60,100 100,0 q60,-20 100,0"
begin="0s"
dur="10s"
repeatCount="indefinite" />
</text>
</svg>
自己動手試一試 »
程式碼解釋
path
屬性定義動畫的路徑begin
屬性定義動畫何時開始dur
屬性定義動畫的持續時間repeatCount
屬性定義動畫播放的次數