How to justify SVG text?

I am trying to justify text inside elements <tspan>using javascript, since SVG is not yet supported text-align: justify. I am sure that I am pretty close to the right solution, but I can’t get the right number of words between words so that each line is justified both on the left and on the right.

Here is the CodePen link to see it in its entirety. Just click on one of the buttons at the bottom of the page to launch the function (scroll down the page to see the buttons).

But I believe the problem here is somewhere here:

First, I look at each element <tspan>and click on its original length to the array.

for (i = 0; i < tspan.length; i++) {
 spanText.push(tspan[i].offsetWidth);
}

Then I save the longest value from this array in a variable

longestSpan = Math.max.apply(Math, spanText);

Then I repeat through each one <tspan>more time and calculate the necessary distance between each word to justify the text of each line to the greatest width<tspan>

for (i = 0; i < tspan.length; i++) {
 var spanLength = longestSpan - tspan[i].offsetWidth;
 var wordCount = tspan[i].innerHTML.split(/\s/).length;
 var wordSpacing = spanLength / (wordCount - 1);
 tspan[i].setAttribute('word-spacing', wordSpacing);
}

As you can see in the link above, the aligned text on each line is a bit off.

Is there a clean SVG solution for this? If not, then how to correctly calculate the interval between each word to get a justified text.

+4
source share
1 answer

Just fixed distance calculation:

wordSpacing = spanLength / (wordCount-1) / 2

Subtracts 1 to get the number of spaces, and finds that the distance is doubled. A word counter is also counted.

+1
source

Source: https://habr.com/ru/post/1622123/


All Articles