SVG get text element width
var bbox = textElement.getBBox();
var width = bbox.width;
var height = bbox.height;
and then set the rect's attributes accordingly.
Link: getBBox()
in the SVG v1.1 standard.
Regarding the length of text the link seems to indicate BBox and getComputedTextLength() may return slightly different values, but ones that are fairly close to each other.
http://bl.ocks.org/MSCAU/58bba77cdcae42fc2f44
document.getElementById('yourTextId').getComputedTextLength();
worked for me in
How about something like this for compatibility:
function svgElemWidth(elem) {
var methods = [ // name of function and how to process its result
{ fn: 'getBBox', w: function(x) { return x.width; }, },
{ fn: 'getBoundingClientRect', w: function(x) { return x.width; }, },
{ fn: 'getComputedTextLength', w: function(x) { return x; }, }, // text elements only
];
var widths = [];
var width, i, method;
for (i = 0; i < methods.length; i++) {
method = methods[i];
if (typeof elem[method.fn] === 'function') {
width = method.w(elem[method.fn]());
if (width !== 0) {
widths.push(width);
}
}
}
var result;
if (widths.length) {
result = 0;
for (i = 0; i < widths.length; i++) {
result += widths[i];
}
result /= widths.length;
}
return result;
}
This returns the average of any valid results of the three methods. You could improve it to cast out outliers or to favor getComputedTextLength
if the element is a text element.
Warning: As the comment says, getBoundingClientRect
is tricky. Either remove it from the methods or use this only on elements where getBoundingClientRect
will return good results, so no rotation and probably no scaling(?)