2012-08-01 74 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