Measure has not generated SVG text in javascript yet

I am trying to create a function that will measure how large a text element will be in an SVG element. The code examples found in Stack Overflow do not work and give a width of zero. If I delay the measurement, I can get the text, but not right away. How to solve this?

var messureSVGtext = function(text, svg, options){
   var text = document.createElementNS(svgns, 'text');
   text.style.fontFamily = options.font;

   text.setAttribute("style",
        "font-family:" + options.font + ";" +
        "font-size:" + options.fontSize + "px;"
   );

   var textNode = document.createTextNode(text);

   text.appendChild(textNode);

   svg.appendChild(text);

   // This does not work
   console.log(text.clientWidth);
      
   //This does
   setTimeout(function(){
      console.log(text.clientWidth);
   }, 100);
}
Run codeHide result
+4
source share
1 answer

You can get the "calculated style" of the element, and then check its width and height.

Give the element an attribute idand after adding it to the DOM, try the following:

var elem1 = document.getElementById("text_elem");
var style = window.getComputedStyle(elem1, null);

console.log(style.width, style.height);


Working example

Svg

<svg
    xmlns="http://www.w3.org/2000/svg"
    version="1.1"
    width="640"
    height="480"
    viewBox="0 0 640 480"
    style="display:block">

    <text id="svg_text" x="20" y="50" style="font-family:Arial; font-size:36px; fill:#BADA55">Hello World!</text>

</svg>


Javascript

function getCompStyle(oid, cbf)
{
    var obj, stl, itv;

    obj = document.getElementById(oid);
    itv = setInterval(function()
    {
        stl = window.getComputedStyle(obj, null);

        if (stl && (stl.width.indexOf('0') != 0))
        {
            clearInterval(itv);
            cbf(stl);
        }
    },0);

}

getCompStyle('svg_text', function(style)
{
    console.log(style.width);
});

To use this example, put SVG in your HTML <body>and JavaScript in a tag <script>under SVG - also in <body>.

+1

All Articles