Text bounding boxes
by Nikos Andronikos
HTML
<svg viewBox="0 0 200 200">
<defs>
<path d="M50,0 L150,100" id="p1" />
<path d="M50,50 L150,150" id="p2" />
</defs>
<text id="text1" x="50" y="100">
<textPath id="textpath1" xlink:href="#p1">ABCDEFG</textPath>
<textPath id="textpath2" xlink:href="#p2">ABCDEFG</textPath>
</text>
</svg>
<p id="log">
</p>
CSS
#log {
font-face: sans-serif;
font-size: 10pt;
}
JavaScript
function log(message) {
var log = document.querySelector("#log");
log.innerHTML = log.innerHTML + message + "<br/>";
}
function svgRectToString(rect) {
return rect.x + "," + rect.y + "," + rect.width + "," + rect.height;
}
try {
var bbox = document.querySelector("#textpath1").getBBox();
log(svgRectToString(bbox));
var r = document.createElementNS("http://www.w3.org/2000/svg", "rect");
r.setAttribute("x", bbox.x);
r.setAttribute("y", bbox.y);
r.setAttribute("width", bbox.width);
r.setAttribute("height", bbox.height);
r.setAttribute("fill", "none");
r.setAttribute("stroke", "skyblue");
document.querySelector("svg").appendChild(r);
} catch (e) {
log(e);
}