Created
March 2, 2020 17:55
-
-
Save innermond/787ce0187986833659fa76b3b50bf7de to your computer and use it in GitHub Desktop.
calculate next y line of a text tspan
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var replaceTextNode = function($parent, txt) { | |
// has a textPath? | |
var $textPath = $parent.getElementsByTagName('textPath'); | |
if ($textPath) $textPath = $textPath[0]; | |
// clean off | |
while ($parent.hasChildNodes()) | |
$parent.removeChild($parent.lastChild); | |
// white space off | |
txt = txt.trim(); | |
// get array of lines | |
var arr = $textPath ? [txt] : txt.split("\n"); | |
var inx = 0; | |
// proper positioning the lines | |
while (arr.length){ | |
var fontHeight = parseFloat($parent.style.getPropertyValue('font-size')); | |
let lh = $parent.style.getPropertyValue('line-height'); | |
let div = lh.slice(-1) == "%" ? 0.01 : 1; | |
var lineHeight = parseFloat(lh)*div; | |
var dy = fontHeight * lineHeight * inx; | |
var $elem = document.createElementNS(xmlns,"tspan"); | |
$elem.textContent = arr.shift(); | |
if ($textPath) { | |
while($textPath.hasChildNodes()) $textPath.removeChild($textPath.lastChild); | |
$textPath.appendChild($elem); | |
$parent.appendChild($textPath); | |
} else { | |
$elem.setAttribute('x', $parent.getAttribute('x')); | |
$elem.setAttribute('y', 1 * $parent.getAttribute('y') + dy ); | |
$parent.appendChild($elem); | |
} | |
inx++; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment