一、stroke-dasharray的基礎知識
stroke-dasharray屬性可以用來控制SVG中的線段虛線,其中,屬性值是一組數字,指定了虛線和實線的長度。在這一方面,stroke-dasharray是非常適合展示多樣化線型、邊框和類似的視覺效果的。
可以通過設置stroke-dasharray的值,改變虛線的樣式,前一個數字表示虛線的長度,後一個數字表示實線的長度。如果數值組合不是偶數,則它們會後續循環使用,直到達到路徑的末端。同樣的, 如果設置所有的值相同的話,則所有的線段都會等長。
<svg width="200" height="200"> <line x1="50" y1="50" x2="150" y2="150" stroke="blue" stroke-width="4" stroke-dasharray="10,5,5"/> </svg>
二、stroke-dasharray的使用場景
stroke-dasharray主要應用於以下場景:
- 線條輪廓
- 虛線邊框
- 運動軌跡
以下是應用於線條輪廓的實例,通過不同的stroke-dasharray值設置,可以得到不同的虛線輪廓樣式。
<svg width="200" height="200"> <line x1="50" y1="50" x2="150" y2="150" stroke="blue" stroke-width="4" stroke-dasharray="10,5"/> <line x1="50" y1="70" x2="150" y2="70" stroke="red" stroke-width="4" stroke-dasharray="15,10"/> <line x1="50" y1="90" x2="150" y2="90" stroke="green" stroke-width="4" stroke-dasharray="20,5,5,5"/> </svg>
三、stroke-dasharray的動畫效果
stroke-dasharray可以用來創建動畫效果,實現路徑畫圖的效果。通過改變stroke-dasharray的值,在不同的時間點展示不同的路徑。
<svg width="200" height="200"> <path fill="none" stroke="#9b4b41" stroke-width="6"> <animate attributeName="stroke-dasharray" values="0 100 350;350 100 0" dur="5s" repeatCount="indefinite" />
<animate attributeName="stroke-dashoffset" values="0;-450" dur="5s" fill="freeze" repeatCount="indefinite" />
<animate id="color" attributeName="stroke" values="#9b4b41;#3f3f3f" begin="0s;color.end+0.5s" dur="5s" repeatCount="indefinite" />
<animate attributeName="d" values="M 20 100 C 20 100 100 20 200 100 C 300 180 180 240 100 150 C 50 100 10 150 20 100;M 50 100 L 600 100" dur="5s" repeatCount="indefinite" /> </path> </svg>
四、stroke-dasharray的應用拓展
在實際案例應用中,stroke-dasharray的應用還可以拓展到其他方面,例如關閉虛線等,創造出更多種類的視覺效果。
以下是一個實現關閉虛線的案例。
<svg width="400" height="100"> <path d="M 0 50 H 400" stroke="#C4DBE0" stroke-width="8"> <animate attributeName="stroke-dasharray" values="20,10; 0,30; 0,30; 0,30;" dur="2s" repeatCount="indefinite" /> </path> </svg>
五、stroke-dasharray的兼容性
可以使用stroke-dasharray來創建虛線動畫,但是這個屬性需要比較老版本的瀏覽器才能支持,例如IE9和較新的版本,各大主流瀏覽器都支持該屬性。因此,在使用stroke-dasharray時,應該優先考慮兼容性問題。
參考資料:
- https://css-tricks.com/almanac/properties/s/stroke-dasharray/
- https://codepen.io/Zoe_Damianaki/pen/yMMybZ
- https://codepen.io/iDVB/pen/ABJyrRj
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/288886.html