SVG 的動畫最有意思的應用之一就是變形,先來一個簡單範例
範例中 path 的每一個點對點的分怖必須一樣,這樣跑起來才不會有問題
<svg width="300" height="300">
<path>
<animate attributeName="d" values="M10,150 Q150,10 150,10 L290,150 L150,290;M150,10 Q290,150 290,150 L150,290 L200,150;M290,150 Q50,50 150,290 L0,0 L0,0;M10,150 Q150,10 150,10 L290,150 L150,290" dur="10s" repeatCount="indefinite"></animate>
<animate attributeName="fill" values="#f00;#ff0;#0f0;#0ff;#00f;#f0f;#f00" dur="13s" repeatCount="indefinite"></animate>
</path>
</svg>
加上 javascript 計算位置,可以做出多邊形變形動畫,和之前用 CSS 做的不同,最後做出來的 SVG 存檔後,就是單純圖檔,完全不需要 javascript 即可互動
實測結果相當有趣,firefox 會不正常顯示,當路徑被動畫修改後,小圓球卻不會修改路徑,還是走本來預設的三角形,chrome 和 safari 則沒有問題。
為了修正 firefox 的問題,用了重寫 html 的技巧,加了一個 [Firefox fix] 的 button
<svg width="300" height="330" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:ev="http://www.w3.org/2001/xml-events">
<g>
<path id="a121002_p1" d="M270,150 L90,253 L89,46 L89,46 L89,46 L89,46 L89,46 z" fill="#0af">
<animate id="a121002_a3" attributeName="d" dur="2s" begin="a121002_b3.click" fill="freeze"></animate>
<animate id="a121002_a4" attributeName="d" dur="2s" begin="a121002_b4.click" fill="freeze"></animate>
<animate id="a121002_a5" attributeName="d" dur="2s" begin="a121002_b5.click" fill="freeze"></animate>
<animate id="a121002_a6" attributeName="d" dur="2s" begin="a121002_b6.click" fill="freeze"></animate>
<animate id="a121002_a7" attributeName="d" dur="2s" begin="a121002_b7.click" fill="freeze"></animate>
<animate id="a121002_a8" attributeName="d" dur="2s" begin="a121002_b8.click" fill="freeze"></animate>
</path>
<circle cx="0" cy="0" r="13" fill="#fa0">
<animateMotion id="a121002_c1" dur="3s" repeatCount="indefinite" rotate="auto">
<mpath xlink:href="#a121002_p1"></mpath>
</animateMotion>
</circle>
<animateTransform attributeName="transform" dur="20s" type="rotate" values="0,150,150;360,150,150" repeatCount="indefinite"></animateTransform>
</g>
<text id="a121002_b3" x="60" y="290">三角形</text>
<text id="a121002_b4" x="120" y="290">四邊形</text>
<text id="a121002_b5" x="180" y="290">五角形</text>
<text id="a121002_b6" x="60" y="315">六角形</text>
<text id="a121002_b7" x="120" y="315">七邊形</text>
<text id="a121002_b8" x="180" y="315">星 形</text>
</svg>
<br>
<button id="a121002_b1" style="font-size:1em">Firefox fix</button>
<script>
$(()=>
{
let i,j,k,m;
let deg;
k=0;
for (j=0;j<6;j++)
{
let hh="";
let x,y;
if (j==5)
deg=360/5*2;
else
deg=360/(j+3);
m="M";
for (i=0;i<7;i++)
{
if ((j==5 && i<5) || (j!=5 && i<(j+3)))
{
x=150+120*Math.cos(3.14*(deg*i+k)/180);
y=150+120*Math.sin(3.14*(deg*i+k)/180);
}
hh+=m+(~~x)+","+(~~y)+" ";
m="L";
}
hh+="z";
$("#a121002_a"+(j+3)).attr("to",hh);
k+=77;
}
$("#a121002_b1").on("click",function()
{
$("#a121002_c1").html($("#a121002_c1").html());
});
})
</script>
沒有留言:
張貼留言