无法测量外部包含的字体

时间:2012-08-01 12:37:13

标签: javascript

我在使用此代码测量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文件中的字体时,测量不起作用,即它测量错误。< / p>

是因为新画布无法“看到”新字体还是其他错误?

1 个答案:

答案 0 :(得分:1)

可能是因为你想在字体满载之前测量字体吗?

在我的例子中,似乎工作正常:Font example