上一篇有簡單介紹一下SVG的元素,雖然沒有介紹很詳細,但是很多部分都和Canvas很相近,所以就不詳細介紹了。
而這篇要介紹svg <g>
這個標簽,它的用途是群組化元素,而被群組後的元素就可以一起被控制,甚至是一起設定樣式。
群組svg
上面的文字與方塊已經算是一個群組了,接下來可以在<g>
這個元素,使用變形(transform)來一起改變外觀,像是以下這樣。
<svg width="100%" height="150">
<g transform="rotate(-10)">
<rect y="10" width="100" height="100" style="stroke: #777; stroke-width: 3; fill: #07B492;"/>
<text x="0" y="130" style="stroke: pink; fill: white"> SVG</text>
</g>
</svg>
像以上這樣,<g>
群組就會被旋轉(-10 deg)。
G 的繼承
在G裡面的元素,都會被外層<g>
所設定的樣式影響,像以下內部的元素沒有設定外框,但卻可以繼承其父層的<g>
樣式。
也就像CSS一樣,如果子元素有設定,則子元素優先。
<svg width="100%" height="150">
<g style="stroke: pink; stroke-width: 5px">
<circle cx="40" cy="35" r="30" style="fill: white;"/>
<circle cx="120" cy="35" r="30" style="fill: white;"/>
<rect x="160" y="5" width="40" height="40" style="fill: white;"/>
<rect x="220" y="5" width="40" height="40" style="fill: red;"/>
</g>
</svg>
G 沒有X,Y
ㄜ,反正就是沒有,這樣似乎有點困擾。
<svg width="100%" height="150">
<g x="40" y="20">
<rect y="10" width="100" height="100" style="stroke: #777; stroke-width: 3; fill: #07B492;"/>
<text x="0" y="130" style="stroke: pink; fill: white"> SVG</text>
</g>
</svg>
向上面這樣,就算有設定<g>
的x,y值,但就是完全沒有反應,如果要控制<g>
的位置,就要用transform
了。
<svg width="100%" height="150">
<g transform="translate(40,20)">
<rect y="10" width="100" height="100" style="stroke: #777; stroke-width: 3; fill: #07B492;"/>
<text x="0" y="130" style="stroke: pink; fill: white"> SVG</text>
</g>
</svg>
利用transform=”translate(40 20)”,就可以位移了,這用法和CSS3 transform相當接近,雖然類似x,y
但本質上還是有所不同。
<svg width="100%" height="150">
<g>
<svg x="40" y="20">
<rect y="10" width="100" height="100" style="stroke: #777; stroke-width: 3; fill: #07B492;"/>
<text x="0" y="130" style="stroke: pink; fill: white"> SVG</text>
</svg>
</g>
</svg>
不過我沒想到的是,svg還可以這樣用,在<g>
裡面再放一個<svg>
,這樣就可以設定他的x,y
,這招太絕了,這樣就可以避免使用translate,使用x,y來設定位置。