1. 程式人生 > >SVG實現描邊動畫

SVG實現描邊動畫

SVG動畫效果

先來放一個自己寫的效果:

在這裡插入圖片描述

OK,現在我們來聊一聊SVG描邊動畫的實現


一、基礎知識

1、stroke相關屬性
  • stroke:表示描邊的顏色。
  • stroke-width :表示描邊的粗細。
  • stroke-linecap :表示描邊端點表現方式。可用值有:butt, round, square, inherit.
    在這裡插入圖片描述
  • stroke-linejoin 表示描邊轉角的表現方式。可用值有:miter, round, bevel, inherit.
    在這裡插入圖片描述
  • stroke-miterlimit :表示描邊相交(銳角)的表現方式。預設大小是4.
  • stroke-dasharray :表示虛線描邊。可選值為:none, <dasharray>, inherit. none表示不是虛線;<dasharray>為一個逗號或空格分隔的數值列表。表示各個虛線段的長度。可以是固定的長度值,也可以是百分比值;inherit表繼承。
  • stroke-dashoffset :表示虛線的起始偏移。可選值為:<percentage>, <length>, inherit. 百分比值,長度值,繼承。
  • stroke-opacity 表示描邊透明度。預設是1。
2、css動畫

語法
animation: name duration timing-function delay iteration-count direction;

  • animation-name:規定需要繫結到選擇器的 keyframe 名稱。
  • animation-duration:規定完成動畫所花費的時間,以秒或毫秒計。
  • animation-timing-function:規定動畫的速度曲線。
  • animation-delay:規定在動畫開始之前的延遲。
  • animation-iteration-count:規定動畫應該播放的次數。
  • animation-direction:規定是否應該輪流反向播放動畫。

二、實戰

HTML程式碼:

<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="454px"
	 height="340px" viewBox="0 0 454 340" enable-background="new 0 0 454 340" xml:space="preserve">
	 		// 設定文字漸變顏色
	 		<linearGradient id="linearGradient_1" x1="0%" y1="0%" x2="100%" y2="0%">
		        <stop offset="0%" style="stop-color:rgb(255,255,0); stop-opacity:1"/>
		        <stop offset="50%" style="stop-color:rgb(255,0,255); stop-opacity:1"/>
		        <stop offset="100%" style="stop-color:rgb(0,255,0); stop-opacity:1"/>
		    </linearGradient>

			<g id="SVG">
				<g fill="none" stroke="url(#linearGradient_1)" stroke-width="2">
					<path d="..."  />
					<path d="..."/>
					<path d="..."/>
				</g>
			</g>
		</svg>

css程式碼主要是實現動畫,讓它動起來,具體如下:

path {
			/*stroke:#000;*/
		  	stroke-dasharray: 25;
		  	stroke-dashoffset: 300;
		 	animation: dash 5s linear  infinite;
}

@keyframes dash {
		  	0%   {stroke-dashoffset: 300;  }
    		100% {stroke-dashoffset: 0;}
}

原始碼:https://github.com/Echo-chu/SVG