Reputation: 976
I'm trying to justify text within <tspan>
elements using javascript since SVG doesn't support text-align: justify
yet. I'm sure that I'm pretty close to the right solution but can't seem to get the correct amount of word-spacing between words so that each line is justified to both the left and right.
Here's a CodePen link to the issue to see it in its entirety. Just click on one of the buttons on the bottom of the page to run the function(scroll down page to see buttons).
But I believe the problem lies somewhere here:
First I'm looping through each <tspan>
element and pushing it's original length to an array.
for (i = 0; i < tspan.length; i++) {
spanText.push(tspan[i].offsetWidth);
}
Then I store the longest value from that array in a variable
longestSpan = Math.max.apply(Math, spanText);
Then I loop through each <tspan>
one more time and calculate the needed spacing between each word to justify the text of each line to the largest <tspan>
's width
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 justified text on each line is slightly off.
Is there a pure SVG solution to this? If not, how do I properly calculate the spacing between each word to get justified text.
Upvotes: 4
Views: 1581