SVG:更改 dy 属性不会更改父文本元素的边框高度



目标是垂直和水平对齐一组tspan元素。

但是,父容器不考虑 dy 值。

这会导致对齐问题。

如果您使用此代码笔的 dy 值,则文本容器高度始终保持不变:https://codepen.io/anon/pen/WLpvrG?editors=1111。

如何获得 tspan 元素的准确边界矩形?

<svg id="textBox1" class="textBox" x="0%" y="0%" width="100%" height="25%">
  <rect class="background" x="0%" y="0%" width="100%" height="100%" fill="gray" fill-opacity="0.5" />
  <text class="tspanGroup" x="0" y="0"><tspan x="50%" dy="0em" text-anchor="middle">tspan line 0</tspan><tspan x="50%" dy="1.5em" text-anchor="middle">tspan line 1</tspan><tspan x="50%" dy="1.5em" text-anchor="middle">tspan line 2</tspan></text>
</svg>

dy 属性表示沿 y 轴的偏移。它不表示调整大小。因此,如果您在第一个<tspan>元素上更改该值,则只需将其向上或向下移动即可。当容器环绕元素时,当您只是移动它们时,它不会改变大小。

如果你想让文本在垂直和水平方向上居中,我建议你看看这里的第二个答案:如何在 SVG 矩形中放置和居中文本。我真的看不出复制/粘贴它有什么意义,哈哈。

好吧,我花了一点时间让它工作,但你来了:

// Wait for document to load so the elements don't return undefined
document.addEventListener("DOMContentLoaded", function(event) {
	// Center the text
	centerText();
	setTimeout(function() {
		// Change font sizes
		document.getElementById('size1').style.fontSize = "12px";
		document.getElementById('size2').style.fontSize = "16px";
		document.getElementById('size3').style.fontSize = "20px";
		// Center the text again
		centerText();
	}, 3000);
});
function centerText(){
	// Get the elements
	const container = document.getElementById('textBox1');
	const textEle = document.getElementById('txt');
	// User getBBox for SVG element data
	const cBox = container.getBBox();
	const tBox = textEle.getBBox();
	// Get width / height of container SVG
	const contHeight = cBox.height;
	const contWidth = cBox.width;
	// Get width / height of TEXT element
	const txtHeight = tBox.height;
	const txtWidth = tBox.width;
	// Set the attributions correctly to center text
	textEle.setAttribute("x", (contWidth/2)-(txtWidth/2));
	textEle.setAttribute("y", (contHeight/2)-(txtHeight/2));
}
<svg id="rootBox" width="375" height="812" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<svg id="textBox1" class="textBox" x="0" y="0" width="100%" height="25%">
		<rect class="background" x="0%" y="0%" width="100%" height="100%" fill="gray" fill-opacity="0.5" />
		<text class="tspanGroup" x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" id="txt">
			<tspan x="50%" dy="0em" id="size1">tspan line 0</tspan>
			<tspan x="50%" dy="1.5em" id="size2">tspan line 1</tspan>
			<tspan x="50%" dy="1.5em" id="size3">tspan line 2</tspan>
		</text>
	</svg>
</svg>

最新更新