2023年7月28日 星期五

SVG Path 動畫

愛心 SVG 圖。 圖片來源:icon-icons.com,有經過修改。
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"  viewBox="0 0 35 35">
	<path stroke="#a9e" fill="none" 
	      d="M22.85,4.04
	         C20.21,3.77,17.7,4.77,16,6.7
	         c-1.7-1.93-4.21-2.93-6.85-2.66
	         C5.14,4.46,2,8.08,2,12.27   
	         c0,2.01,0.75,3.93,2.11,5.42l7.8,8.51
	         C12.96,27.34,14.45,28,16,28
	         s3.04-0.66,4.09-1.8
	         l7.8-8.51
	         C29.25,16.2,30,14.28,30,12.27   
	         C30,8.08,26.86,4.46,22.85,4.04z " />
</svg>

如果要針對其線條(d attribute)做動畫,需要用到 stroke dasharray

根據計算,這條 path 的長度是 83.302001953125px

(83.302001953125 這數字是靠 以下方式取得)

document.querySelector("svg path").getTotalLength()

設定不同的 stroke dasharray,線條可以有如下變化(上面的粗體文字是 stroke dasharray 的值)

0 75 8.302001953125
0 60 23.302001953125
0 35 48.302001953125
0 10 73.302001953125

依照這樣子,就能設置 animation

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"  viewBox="0 0 35 35" >
	<path stroke="#a9e" fill="none" 
	      d="M22.85,4.04
	         C20.21,3.77,17.7,4.77,16,6.7
	         c-1.7-1.93-4.21-2.93-6.85-2.66
	         C5.14,4.46,2,8.08,2,12.27   
	         c0,2.01,0.75,3.93,2.11,5.42l7.8,8.51
	         C12.96,27.34,14.45,28,16,28
	         s3.04-0.66,4.09-1.8
	         l7.8-8.51
	         C29.25,16.2,30,14.28,30,12.27   
	         C30,8.08,26.86,4.46,22.85,4.04z " >
		<animate attributeName="stroke-dasharray"
		         values="0 83 0.302001953125;
		                 0 75 8.302001953125;
		                 0 60 23.302001953125;
		                 0 35 48.302001953125;
		                 0 15 68.302001953125;
		                 0 0 83.302001953125"
		         dur="5s"
		         repeatCount="indefinite" />
	</path>		
</svg>

參考資料

沒有留言:

張貼留言