Skip to content

Instantly share code, notes, and snippets.

@innermond
Created March 4, 2020 10:09
Show Gist options
  • Save innermond/e5a315843874043e13a66cb8e19c078c to your computer and use it in GitHub Desktop.
Save innermond/e5a315843874043e13a66cb8e19c078c to your computer and use it in GitHub Desktop.
svg text elements aligned to center
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