Locke
Locke

Reputation: 13

Inline svg + webfont calculates wrong width

At the moment I'm trying to render some projectnames as svg on my website. i use a webfont and on the first load, my script calculates the wrong width for the inline svg, as soon as I reload my website, the width is calculated properly. (for reproducing the error its enough to delete the browser cache)

<script>     
            var startup81 = function (evt) {
                var svgNS = "http://www.w3.org/2000/svg";
                var txtNode = document.createTextNode("D");
                text = document.createElementNS(svgNS,"text");
                text.setAttributeNS(null,"x",5);
                text.setAttributeNS(null,"y",130); 
                text.setAttributeNS(null,"style","font-family:MatryoshkaL; font-size:185px;");
                text.setAttributeNS(null,"fill","url(#pattern81)");
                text.appendChild(txtNode);                                                
                document.getElementById("main81").appendChild(text);

                var width;
                width = text.getComputedTextLength() +3;
                var elem = evt.target;
                elem.setAttribute("width", + Math.round(width));
            }        
        </script>


        <svg id="main81" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" onload="startup81(evt)" height="168" ><defs id="defs81"><pattern  x="-108" y="-71" id="pattern81" width="200" height="160" patternUnits="userSpaceOnUse" patternTransform="rotate(-35)"><image id="image81" preserveAspectRatio="none" height="160" width="200" xlink:href="http://i.imgur.com/WpE9bNB.jpg"></image></pattern></defs></svg>

As there a way to get the width of each svg rendered on the first visit?

thanks for your help

Upvotes: 1

Views: 125

Answers (1)

shershen
shershen

Reputation: 9993

I've tried to make a small demo out of your code snippets for each letter here - http://jsfiddle.net/shershen08/8ujc2toh/ . It doesn't load the webfont file (due to CORS) and there is no second load needed to define the correct size.

So my assupmtion is that when your onload="startup81(evt)" runs on svg elements, the webfont file (that one http://marcdasing.de/wp-content/themes/typo/webfonts/2E3E39_0_0.eot in your CSS) is not yet loaded fully and that leads to incorrect width calculation for some letters.

To avoid that you need to run those 'startup81'..'startup82'..etc functions when webfont is loaded. For implementing that you can explore 2 options: 1) simply set reasonable timeout

$(document).ready(function(){
  setTimeout(function(){
    //..
    startup80();
    startup81();
    startup82();
    //all you separate svg functions
    //could be done in more clearer way btw, but it's not the point
  }, 500); // 0.5sec after page DOM is loaded
})

2) or use modern browsers APIs to catch that

Upvotes: 1

Related Questions