SVG:理解stroke-dasharray和stroke-dashoffset屬性

嚴博藝發表於2019-03-17

1.前言

最近剛學習SVG看到一個霓虹燈的動畫效果感覺很炫酷,便按照文章巧了下來,雖然實現了但是對於 stroke-dasharray和stroke-dashoffset屬性還不是特別清楚,通過查詢資料和看文件終於理解,希望對大家有幫助

2.屬性作用

我們知道SVG是在畫畫,那麼stroke屬性系列就是畫筆。 stroke-dasharraystroke-dashoffset是stroke的兩個屬性

stroke-dasharray

定義

官方文件給出的解釋是:The stroke-dasharray property controls the pattern of dashes and gaps used to form the shape of a path's stroke. 按照我的理解:stroke-dasharray就是控制畫筆的虛實,通過實線和虛線的來控制畫

作用範圍

可以在shape(形狀)和text content elements(字型元素)上起作用

引數

接下來重點講下他的引數,這裡是可能是大家最無法理解的地方。dasharray顧名思義就是線段的陣列,他的引數可以是一個陣列,每個引數又有什麼含義呢 官方文件解釋: **The first value and every second value in the list after it specifies the length of a dash, and every other value specifies the length of a gap between the dashes. ** 意思就是單數值代表實線的長度,雙數值代表虛線的長度

例子

下圖中每個大方格邊長是100px,線段的初始長度是200px

stroke-dasharray: 0;

stroke-dasharray: 0;
複製程式碼

此時stroke-dasharray不起作用,注:當他的引數<=0時該屬性將失效

troke-dasharray: 20;

stroke-dasharray: 20;
複製程式碼

可以看出來實線的長度確實是20px,為什麼會有虛線也是20呢,這裡官方文件給出的解釋是:If the list has an odd number of values, then it is repeated to yield an even number of values. 也就是說如果引數個數是單數是預設會複製一份引數,比如1 2 3 將會變成1 2 3 1 2 3六個引數

troke-dasharray: 120;

troke-dasharray: 120;
複製程式碼

按理來說在一個引數的情況下虛線和實線應該是等長的這裡不等長,很好理解描繪的是線段,超出部分將會隱藏。但是如果是個封閉圖形,結果也是相同的

圓

這裡是一個引數的多個引數也一樣的,本質上就是根據實線和虛線的長度依次描繪,這裡就不測試了。

另外他的引數還可以是百分比,這樣就不需要知道總長就能精確使用了,如果要知道總長可以使用js獲取Path元素的pathLength屬性

var path = document.querySelector('path');
var length = path.getTotalLength();
複製程式碼

stroke-dashoffset

理解了stroke-dasharray那麼理解stroke-dashoffset就簡單了

定義

官方文件:The stroke-dashoffset property specifies the distance into the repeated dash pattern to start the stroke dashing at the beginning of the path. If the value is negative, then the effect is the same as dash offset d: 意思就是:相對於繪製的起點偏移的量,正值(向右或者順時針偏移),負值(向左或者逆時針)

偏移量計算公式:

d = s - | 'stroke-dashoffset' | mod s
d:偏移量  s:線段總長度  'stroke-dashoffset':引數值
複製程式碼

從公式我們可以看出偏移量是一個區間的值,無論引數值多大,偏移量不會大於線段總長度

作用範圍

和上面一樣可以在shape(形狀)和text content elements(字型元素)上起作用 並且可支援動畫,從而實現炫酷的效果

引數

另外由於我們實際設定stroke-dashoffset引數的時候不會大於線段長度,用上面的公式計算未免麻煩,我們可以逆向理解,偏移量就是正值(向左或者逆時針)/負值(向右或者順時針)偏移stroke-dashoffset引數的大小。

例子

stroke-dashoffset: 0;

stroke-dasharray: 120;
stroke-dashoffset: 0;
複製程式碼

上面為初始狀態,引數為0,沒偏移

stroke-dashoffset: 20;

stroke-dasharray: 120;
stroke-dashoffset: 20;
複製程式碼

當引數為20如果按照官方文件的理解就是:d = 200 - 20 mod 200 = 180 向右偏移了180px 而從圖中明顯可以看到線段往左移動了20px,所以我們可以理解為想左偏移了引數值,封閉圖形是逆時針,大家自己可以去試試。負值同理如下圖

stroke-dashoffset: -20;

stroke-dasharray: 120;
stroke-dashoffset: -20;
複製程式碼

總結

到這裡我們基本就理解了stroke-dasharray和stroke-dashoffset這兩個屬性的作用和引數的意義,由於stroke-dashoffset是閉包迴圈的,我們就可以使用動畫效果做出炫酷的SVG效果如: 霓虹燈字型

第一次在掘金寫文章,排版問題多多見諒!

參考資料

張鑫旭-鑫空間 W3官方文件

相關文章