2017-09-02 55 views
1

我試圖使用javascript,但上下文getImageData返回任何字符的像素密度總是一個數組,這似乎是一個間距黑色矩形(RGB = [0,0, 0]總是)。fillText返回後得到畫布像素0

有誰能告訴我whant我做錯了嗎?

var dcanvas = document.getElementById('char-canvas'), 
 
    dcontext = dcanvas.getContext('2d'); 
 

 
function fontDensity(c) { 
 
    dcanvas.height = 30; 
 
    dcanvas.width = 30; 
 
    dcontext.clearRect(0, 0, dcanvas.width, dcanvas.height); 
 
    dcontext.font = "15px monospace"; 
 
    dcontext.fillStyle = "black"; 
 
    dcontext.textAlign = "center"; 
 
    dcontext.textBaseline = "middle"; 
 
    dcontext.fillText(c, dcanvas.width/2, dcanvas.height/2); 
 
    var imgd = dcontext.getImageData(0, 0, dcanvas.width, dcanvas.height), 
 
    pix = imgd.data, 
 
    density = 0; 
 
    // Read canvas pixels RGBA! 
 
    for (var i = 0, n = pix.length; i < n; i += 4) { 
 
    density += (pix[i] + pix[i + 1] + pix[i + 2])/3; 
 
    } 
 
    //density /= pix.length; 
 
    return density; 
 
} 
 

 
console.log(fontDensity("a"));
canvas { 
 
    border: 1px solid #000; 
 
    display: block; 
 
    margin: 20px auto; 
 
}
<canvas id="char-canvas" width="30" height="30"></canvas>

回答

1

默認像素值是黑色透明的,所以你將永遠有RGB返回0,當顏色爲黑色。

爲了區別,你需要使用alpha通道:

var density = (pix[i] + pix[i + 1] + pix[i + 2]) * (pix[i + 3]/255)/3; 
//            ^^^^^^^^^^^^^^^^^^^^ 

這僅僅是一個辦法做到這一點,當然。爲避免消除鋸齒像素成爲計算的一部分,只需使用閾值即可。

+0

我是個白癡......畫布的默認「顏色」不是白色的......謝謝! –

1

搞怪,黑回報的零RGB 0是黑色的。 不需要setTimeout。

//Globals 
 

 
density = 0; 
 
dcanvas = null; 
 
dcontext = null; 
 
imgd = null; 
 
pix = null; 
 

 
//make calculation 
 
function GET() { 
 
    
 
    for (var i = 0, n = pix.length; i < n; i += 4) { 
 
    density += (pix[i] + pix[i + 1] + pix[i + 2])/3; 
 
    } 
 
    console.log(density) 
 
    
 
} 
 

 

 

 
function fontDensity(c) { 
 
    dcanvas.height = 30; 
 
    dcanvas.width = 30; 
 
    dcontext.clearRect(0, 0, dcanvas.width, dcanvas.height); 
 
    dcontext.font = "15px monospace"; 
 
    dcontext.fillStyle = "#100000"; 
 
    dcontext.textAlign = "center"; 
 
    dcontext.textBaseline = "middle"; 
 
    dcontext.fillText(c, dcanvas.width/2, dcanvas.height/2); 
 
//dcontext.fillRect(0,0, dcanvas.width , dcanvas.height); 
 
    imgd = dcontext.getImageData(0, 0, dcanvas.width , dcanvas.height); 
 
    pix = imgd.data; 
 
    GET() 
 
    
 
} 
 

 
window.onload = function(){ 
 

 
dcanvas = document.getElementById('char-canvas'); 
 
dcontext = dcanvas.getContext('2d'); 
 

 
    fontDensity("a") 
 

 
    
 
};
canvas { 
 
    border: 1px solid #000; 
 
    display: block; 
 
    margin: 0px auto; 
 
}
<canvas id="char-canvas" width="30" height="30"></canvas>

+0

感謝yyou的提示! –