我試圖使用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>
我是個白癡......畫布的默認「顏色」不是白色的......謝謝! –