2012-08-01 80 views
1

我有問題測量我所使用此代碼包含CSS一個字體的高度:麻煩測量外部包括字體

measureFontHeight3: function(font) 
    { 
     var left = 0; 
     var top = 0; 
     var height = 50; 
     var width = 50; 

     // Draw the text in the specified area 
     var canvas = ig.$new('canvas'); 
     canvas.width = width; 
     canvas.height = height; 
     var ctx = canvas.getContext('2d'); 
     ctx.font = font; 
     ctx.textBaseline = 'top'; 
     ctx.fillText('gM', 0,0); 

     // Get the pixel data from the canvas 
     var data = ctx.getImageData(left, top, width, height).data, 
      first = false, 
      last = false, 
      r = height, 
      c = 0; 

     // Find the last line with a non-white pixel 
     while(!last && r) 
     { 
      r--; 
      for(c = 0; c < width; c++) 
      { 
       if(data[r * width * 4 + c * 4 + 3]) 
       { 
        last = r; 
        break; 
       } 
      } 
     } 

     // Find the first line with a non-white pixel 
     while(r) 
     { 
      r--; 
      for(c = 0; c < width; c++) 
      { 
       if(data[r * width * 4 + c * 4 + 3]) { 
        first = r; 
        break; 
       } 
      } 

      // If we've got it then return the height 
      if(first != r) 
       { 
        var result = last - first; 
        console.log("3: " +result); 
        return result; 
       } 
     } 

     // We screwed something up... What do you expect from free code? 
     return 0; 
    }, 

當我測量該系統已經安裝該字體,則該函數是相當準確的,但是當我嘗試測量一個CSS文件中包含的字體時,測量不起作用,即測量錯誤。

是因爲新的畫布無法「看到」新字體或是其他錯誤?

+0

您可以包括jsfiddle.net例子嗎? – 2012-08-01 13:01:11

+0

什麼是jsfiddle.net? 如果我測量一個名爲「30 pt Trebuchet MS」的字體,它會顯示正確的高度,但如果我在CSS文件中包含名爲Visitor的字體並嘗試測量該字體,它會給我一個不正確的高度。它幾乎看起來像畫布不使用Visitor字體,而是一個標準字體。 – user1069703 2012-08-02 06:48:41

+0

[jsfiddle.net](http://jsfiddle.net)是javascript/html/css的保存和共享功能的遊樂場,它可以匿名使用,看看它對分享像這樣的問題非常有用,因爲其他人將能夠重現相同的問題。 – 2012-08-02 08:16:33

回答

1

難道是因爲你想在字體完全加載之前測量字體嗎?

在我的例子這似乎是做工精細:Font example

+0

感謝您將代碼放在jsFiddle中。 我可以看到,我有時在JSFiddle中繪製字體時會得到正確的字體,有時我不會。但該方法返回一個不同的高度,取決於是否加載了正確的字體。這清楚地告訴我,我正在嘗試在完全加載之前測量字體。 有沒有一種方法可以檢查字體是否已經完全加載? – user1069703 2012-08-03 14:49:55

+0

看看[這裏](http://stackoverflow.com/questions/4383226/using-jquery-to-know-when-font-face-fonts-areloaded)或[there](http:// stackoverflow .COM /問題/ 4383226 /使用-jquery的對知識的時候,字體面的字體,被加載) – 2012-08-03 15:29:22