最近作了一個關於SVG的應用的技術分享網站svgtrick.com,會同步一些文章到這裏來,更多的關於SVG方面的技術知識能夠去網站看看。css
在SVG中邊框這一屬性雖然看似簡單,但實則是大有天地,今天就來深扒下SVG中的邊框的一些基礎知識。svg
在SVG中,邊框最多見的應用就是用來指定路徑或者是其它形狀的邊框的顏色以及寬度。使用方法跟CSS差很少,好比:動畫
<svg viewBox="0 0 300 10"> <line x1="0" y1="0" x2="300" y2="0" stroke="black" stroke-width="10" /> </svg>
上面就指定來這條直線邊框的顏色是黑色以及它的寬度爲10像素。網站
在SVG中也能夠像CSS中那樣指定邊框爲虛線要用到屬性stroke-dasharray。troke-dasharray屬性的參數,是一組用逗號分割的數字組成的序列。須要注意的是,這裏的數字必須用逗號分割,雖然也能夠插入空格,可是數字之間必須用逗號分開。每一組數字,第一個用來表示實線,第二個用來表示空白。spa
<svg viewBox="0 0 300 10"> <line x1="0" y1="0" x2="300" y2="0" stroke="black" stroke-width="10" stroke-dasharray="5" /> </svg>
上面只有一個數字5,則表示會先畫5px實線,緊接着是5px空白,而後又是5px實線,從而造成虛線。若是你想要更復雜的虛線模式,你能夠定義更多的數字,好比:code
<svg viewBox="0 0 300 10"> <defs> <style> line#es { stroke: black; stroke-width: 5; stroke-dasharray: 5,20; } </style> </defs> <line id="es" x1="0" y1="0" x2="300" y2="0" /> </svg>
上面代碼表示會先畫5px實線,緊接着是20px空白,而後又是5px實線,從而造成虛線。xml
若是是三個數字呢:rem
<svg viewBox="0 0 300 10"> <defs> <style> line#es { stroke: black; stroke-width: 5; stroke-dasharray: 5,20,5; } </style> </defs> <line id="es" x1="0" y1="0" x2="300" y2="0" /> </svg>
這種狀況下,數字會循環兩次,造成一個偶數的虛線模式。因此該路徑首先是5px實線,而後是20px空白,而後是5px實線,接下來循環這組數字,造成5px空白、20px實線、5px空白。而後這種模式會繼續循環。get
stroke-dashoffset,定義虛線開始的位置。animation
line#dashstart { stroke: black; stroke-width: 5; stroke-dasharray: 5, 20, 5; stroke-dashoffset: 20; }
上面代碼就定義裏虛線是從20px像素的位置開始的。
利用storke-dashoffset和stroke-dasharray再配合CSS3的animation就可讓SVG線條產生像手畫出來同樣的動畫效果。
來先看一張圖:
當咱們有一段長度爲300的線條時,咱們指定它的storke-dashoffset的值跟它的stroke-dasharray的值同樣,這時候線條時從300像素的開始繪製,而咱們整個的線條也只有300像素,因此這個時候線條時不可見的。而當咱們指定storke-dashoffset的值從300慢慢的變化到0的時候,則線條也會從0的位置重新開始繪製,因此就像手畫出來同樣。配合CSS3就能夠模擬實現手繪的動畫效果。
@keyframes strokeanim { to { stroke-dashoffset: 0; } } line#dashstart { stroke: hsl(260, 50%, 30%); stroke-width: 15; stroke-dasharray: 300; stroke-dashoffset: 300; animation: strokeanim 2s alternate infinite; }
以下圖所示:
利用這個能夠製造不少有趣的動畫效果。
好比在SVG中有各類各樣的形狀,下面就以矩形爲例,結合上面說的方法,能夠實現下面的動畫效果:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 300 200"> <style type="text/css"> @keyframes marchingants { to { stroke-dashoffset: 19; } } rect#strokedrect { stroke: hsl(260, 50%, 90%); fill: white; stroke-width: 7; stroke-dasharray: 10; animation: marchingants 1s forwards infinite linear; } </style> <rect id="strokedrect" x="0" y="0" width="300" height="200" /> </svg>
以下圖所示:
本文中的實例主要來自於這篇文章原文地址有刪減。