Created
March 4, 2020 10:09
-
-
Save innermond/e5a315843874043e13a66cb8e19c078c to your computer and use it in GitHub Desktop.
svg text elements aligned to center
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 centerTextAlign = function($elem) { | |
if ($elem.tagName != 'text') return false; | |
var bb=$elem.getBBox(); | |
var x0=bb.x,y0=bb.y; | |
$elem.style.setProperty('text-align', 'center'); | |
$elem.style.setProperty('text-anchor', 'middle'); | |
bb=$elem.getBBox(); | |
var x1=bb.x,y1=bb.y; | |
// position changed because of alignment alteration | |
var offset = x0 - x1; | |
// correct position | |
var lst=$elem.transform.baseVal; | |
var tsf=$svg.createSVGTransform(); | |
tsf.setTranslate(offset,y0-y1); | |
lst.appendItem(tsf); | |
lst.consolidate(); | |
return true; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment