我有問題測量我所使用此代碼包含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