2024年6月7日 星期五

SVG 文字置中

首先是個普通的 SVG:

Hi! quick fox
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 200 200" width="300">
	<g fill="none" stroke="rgba(22, 22, 22, 0.5)">
		<path d="M 90 90 L 110 110 Z"/>
		<path d="M 110 90 L 90 110 Z"/>
	</g>
	<text font-family="Arial, sans-serif" x="100" y="100" font-size="30">Hi! quick fox</text>
</svg>

為了方便辨識,在 (100, 100) 的位置打了個叉。



上面的 SVG 可以看出來,文字無論是 x 軸還是 y 軸都沒有置中。



如果要縱向置中,需要用到 SVG attribute——text-anchor,如下:

Hi! quick fox
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 200 200" width="300">
	<g fill="none" stroke="rgba(22, 22, 22, 0.5)">
		<path d="M 90 90 L 110 110 Z"/>
		<path d="M 110 90 L 90 110 Z"/>
	</g>
	<text font-family="Arial, sans-serif" x="100" y="100" font-size="30" 
		text-anchor="middle"
	>Hi! quick fox</text>
</svg>


如果要橫向置中,則需要用到另一個 SVG attribute——dominant-baseline,如下:

Hi! quick fox
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 200 200" width="300">
	<g fill="none" stroke="rgba(22, 22, 22, 0.5)">
		<path d="M 90 90 L 110 110 Z"/>
		<path d="M 110 90 L 90 110 Z"/>
	</g>
	<text font-family="Arial, sans-serif" x="100" y="100" font-size="30" 
		dominant-baseline="middle"
	>Hi! quick fox</text>
</svg>


縱向和橫向都置中:

Hi! quick fox
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 200 200" width="300">
	<g fill="none" stroke="rgba(22, 22, 22, 0.5)">
		<path d="M 90 90 L 110 110 Z"/>
		<path d="M 110 90 L 90 110 Z"/>
	</g>
	<text font-family="Arial, sans-serif" x="100" y="100" font-size="30" 
		text-anchor="middle" dominant-baseline="middle"
	>Hi! quick fox</text>
</svg>

參考資料

Dominant-Baseline. (n.d.). MDN. https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/dominant-baseline
Text-Anchor. (n.d.). MDN. https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/text-anchor
Montoro, A. (n.d.). Re: How to Place and Center Text in an SVG Rectangle (L. U. Matthews, Ed.). Stack Overflow. https://stackoverflow.com/a/31522006

沒有留言:

張貼留言