今天是假日,就來個簡單的收尾,來介紹這幾天的混合用法,當然,我不會想在假日看到<Path>
…。
會先介紹之前Blog所提到的stroke animation,在介紹marker,marker是製作一個圖形,套用在line、path、polygon等等的線段上,可以定義在起始點、終點、以及轉折點上。
Stroke Dash
參考來源
http://cssdeck.com/labs/ironman-svg-line-animation
作者是把這效果用在描繪鋼鐵人上,做得很酷,而本篇是介紹它的原理。
stroke-dasharray + stroke-dashoffset
stroke-dasharray
是把stroke做成了是虛線的效果,線段會被拆成線段、空白、線段、空白,效果就像下面這樣。
line {
stroke-dasharray: 60;
}
如上顯示,線段被拆成60px
的line
在空60px
的space
。
stroke-dashoffset
而stroke-dashoffset
屬性是將上面的虛線推移,兩者會有以下幾點特性:
- 推移後,dasharray還是會保持循環。
- dashoffset的值不會大於dasharray。
- 如果dashoffset 等於 dasharray,線段起始點會是空白。
所以這部分就再加上40的stroke-dashoffset
來看看結果。
line.l2{
stroke-dashoffset: 40;
}
如果兩者數值相等,線段的起始點就會呈現空白,這邊先設較小的值(200)。
line.l3{
stroke-dasharray: 200;
stroke-dashoffset: 200;
}
如果數值相當的大,就能夠將整個線段隱藏。
結合CSS aniamtion
aniamtion 相關的瀏覽器前輟詞問題,可參考/css/2013/10/17/css-animation-keyframe/
這邊就show重要的CSS code,利用上面的原理將線段隱藏,然後透過animation將線段拉回來,這樣就會有動態描繪的感覺。
//sass
.stroke
stroke-dashoffset: 2000
stroke-dasharray: 2000
//動畫效果 10秒 線性動畫 無限循環
.ani
animation: circle-draw 10s linear infinite
//keyframes的值
//將dashoffset拉回至0
@keyframes circle-draw
80%
stroke-dashoffset: 0
<svg class="stroke ani" height="400" width="100%" >
<g>
<circle cx="200" cy="200" r="10"/>
<circle cx="200" cy="200" r="20"/>
<circle cx="200" cy="200" r="30"/>
<circle cx="200" cy="200" r="40"/>
<circle cx="200" cy="200" r="50"/>
<circle cx="200" cy="200" r="60"/>
<circle cx="200" cy="200" r="70"/>
<circle cx="200" cy="200" r="80"/>
<circle cx="200" cy="200" r="90"/>
<circle cx="200" cy="200" r="100"/>
<circle cx="200" cy="200" r="110"/>
<circle cx="200" cy="200" r="120"/>
<circle cx="200" cy="200" r="130"/>
<circle cx="200" cy="200" r="140"/>
<circle cx="200" cy="200" r="150"/>
<circle cx="200" cy="200" r="160"/>
</g>
</svg>
以上的SVG code,當然這也可以用Illustrator來繪製,只要把svg code換掉就可以了。
注意,儘量不要在網頁上做無限循環的重復播放,很耗效能。
回到Marker
根據上一篇的介紹,Marker做法和漸層相當的類似,除了需要定義id外,一樣需要寬與高,不過marker還多了refx
和 refy
,這是用來給路徑套用時所參照的相對位置;所以下面的範例refx="5" refy="5"
,也是要給circle
使用的位置。
在定義完後,Polyline的style內加上marker-mid: url(#midCircle);
就完成對marker的套用,當然這篇的另一個範例所使用的CSS(Class)也可以繼續套用在這範例上。
<svg width="100%" height="200">
<defs>
<marker id="midCircle" markerWidth="8" markerHeight="8" refx="5" refy="5">
<circle id="dot" cx="5" cy="5" r="3" fill="red" />
</marker>
<marker id="endCircle" markerWidth="8" markerHeight="8" refx="5" refy="5">
<circle id="dot" cx="5" cy="5" r="3" fill="white" stroke="red" />
</marker>
</defs>
<polyline class="stroke ani" points="20,140 60,120 80,100 100,95 120,120 140,80 160,85 180,125 200,80 220,95 240,140 260,145 280,120 300,95 320,88 340,80 360,102"
style="fill:none;
stroke:red;
stroke-width:1;
marker-mid: url(#midCircle);
marker-end: url(#endCircle);
" />
</svg>
這樣就做出簡易的折線圖,SVG的觀念和一般的Html有些的不同,這次的鐵人賽主要介紹的不是SVG,只是略微帶過,有興趣的可以參考 http://tutorials.jenkov.com/svg/index.html 所寫的SVG教學。
台灣也有高手是介紹SVG的也可以多向他學習http://www.oxxostudio.tw/index.html?tag-web,不止基礎的教學,還包含許多豐富的技法,令人歎為觀止(跪)。
接下來開始,就會進入D3js的世界,有許多沒辦法做很好的地方,就試試看用硬派的方式去處理吧。