SVG: изменение атрибута dy не меняет высоту ограничивающего прямоугольника для родительского текстового элемента - PullRequest
0 голосов
/ 21 декабря 2018

Целью является выравнивание по вертикали и горизонтали группы элементов tspan.

Однако родительский контейнер не учитывает значения dy.

Это вызывает проблемы с выравниванием.

Если вы играете со значениями dy этого Codepen, высота текстового контейнера все время остается одинаковой: 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>

1 Ответ

0 голосов
/ 21 декабря 2018

Атрибут 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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...