2015-11-02 55 views
0

此刻,我正在嘗試在我的網站上呈現一些項目名稱作爲svg。我使用webfont,並在第一次加載時,我的腳本計算內聯svg的錯誤寬度,只要我重新加載我的網站,寬度計算得當。 (用於再現錯誤的足夠刪除瀏覽器緩存)Inline svg + webfont計算錯誤寬度

<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> 

至於有沒有辦法讓呈現在首次訪問每個SVG的寬度是多少?

感謝您的幫助

+0

如果你把這裏做這個轉換的代碼,而不是鏈接到它的方便多了你的網頁。 – shershen

+0

對不起,我編輯我的第一篇文章,並添加我的代碼 – Locke

回答

0

我試圖做一個小的演示出你的代碼片段在這裏每個字母 - http://jsfiddle.net/shershen08/8ujc2toh/。 它不加載webfont文件(由於CORS),並且不需要第二次加載來定義正確的大小。

所以我assupmtion是,當你onload="startup81(evt)"運行在SVG元素中,web字體文件(在你的CSS一個http://marcdasing.de/wp-content/themes/typo/webfonts/2E3E39_0_0.eot)是尚未加載完全,並導致不正確的寬度計算一些字母。

爲了避免在加載webfont時需要運行那些'startup81'..'startup82'.. etc等功能。爲了實現,你可以探索2種選擇: 1)簡單地設定合理的超時

$(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),或使用modern browsers APIs to catch that

+0

謝謝,與超時的想法是偉大的。我只是不知道它放在哪裏。 我爲每個字母運行上面的代碼,所以是否有可能將超時代碼直接放在我的代碼片段中?如果我將你的代碼包裹在我的函數中,它就不再工作了。 – Locke

+0

好的我想通了,因爲瀏覽器會設置它的svg寬度的標準值,所以不可能只設置javascript被延遲。 svg是在網站的html部分中創建的,現在我只是在javascript中創建了洞svg,並將計時器設置爲500毫秒,其工作效果很好。 非常感謝 – Locke