我有问题测量我所使用此代码包含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文件中包含的字体时,测量不起作用,即测量错误。
是因为新的画布无法“看到”新字体或是其他错误?
您可以包括jsfiddle.net例子吗? – 2012-08-01 13:01:11
什么是jsfiddle.net? 如果我测量一个名为“30 pt Trebuchet MS”的字体,它会显示正确的高度,但如果我在CSS文件中包含名为Visitor的字体并尝试测量该字体,它会给我一个不正确的高度。它几乎看起来像画布不使用Visitor字体,而是一个标准字体。 – user1069703 2012-08-02 06:48:41
[jsfiddle.net](http://jsfiddle.net)是javascript/html/css的保存和共享功能的游乐场,它可以匿名使用,看看它对分享像这样的问题非常有用,因为其他人将能够重现相同的问题。 – 2012-08-02 08:16:33