第 361 篇 · 第 14 卷 前端,沒有極限 2026 年 6 月 9 日 · 台北
ls -lt ./posts --since=2013 REC · node 361 · uplink

svg

SVG 線段

2014 年 05 月 05 日 · 2 分鐘閱讀 · By Wang Casper

這次要練習的是SVG的linepolylinepolygon,這三個都有點類似,但是Polyline和Polygon兩者之間卻有線與塊之間的差異。

Line

line簡單來說就是兩個點之間的線段,所以起點是x1、y1,終點則是x2、y2。

<svg width="100%" height="100">
	<line x1="0" y1="0" x2="300" y2="0" style="stroke: pink; "/>
	<line x1="0" y1="10" x2="300" y2="10" x3="200" y3="30" style="stroke: pink; "/>
</svg>

但是line只能當做兩點間的線段,就算寫了x3y3都是沒用的喔(如上)。

Polyline

Polyline我查到的中文翻譯是折線,它主要是繪製多點線段。

<svg width="100%" height="100">
	<polyline points="40,0 60,60 0,60" style=" stroke:red; stroke-width:2"/>
	<polyline points="140,0 160,60 100,60" style="fill:none; stroke:red; stroke-width:2"/>
	<polyline points="240,0 260,60 200,60 240,0" style="fill:none; stroke:red; stroke-width:2"/>
</svg>

Polyline有點類似Illustrator的鋼筆工具(但還不能繪製弧線),在線段之間還能填入色彩,但特別要注意的是他並不是自動封閉線段。

Polygon

Polygon中文翻譯為多邊形,用來繪製不少於3個邊的圖形。

<svg width="100%" height="100">
	<polygon points="40,0 60,60 0,60" style=" stroke:red; stroke-width:2"/>
	<polygon points="140,0 160,60 100,60" style="fill:none; stroke:red; stroke-width:2"/>
	<polygon points="240,0 260,60 200,60 240,0" style="fill:none; stroke:red; stroke-width:2"/>
</svg>

這邊我刻意用和polyline相同的code,兩者只有標簽不同,從這樣比較能夠比對出兩個不同的地方,重點就是Polygon會自動連接最後點到第一個點