简体   繁体   中英

Unable to get color of pixels in canvas

The canvas is divided in two parts. Left part is black and right part is white. I am using the following code to find white pixels in a specific line but it logs nothing to the console.

This is my code for turning the left half of the canvas black.

ctx.beginPath();
ctx.rect(0, 0, cw/2, ch);
ctx.fillStyle = 'black';
ctx.fill();

This is the code I am using to get pixel data:

var imgd = ctx.getImageData(0, 300, 600, 2);
var pix = imgd.data;
var white_count = 0;
for (var i = 0, n = pix.length; i < n; i += 4) {
    var red = pix[i]; // red
    var green = pix[i+1]; // green
    var blue = pix[i+2]; // blue
    console.log(red);
    if(red == 255 && green == 255 && blue == 255) {
        white_count += 1;
    }
}

At least a few of the red values should have been 255 but they are all 0. Why is that happening? This is my JSFiddle : https://jsfiddle.net/83Lb96vp/

I think you are doing the getImageData dimensions wrong.

It need to be ctx.getImageData(sx, sy, sw, sh); .

take a look at this fiddle:

 console.clear(); var c = document.getElementById('c'); var ctx = c.getContext('2d'); var sizeMod = 4; // one "sqare" is "sizeMod" * "sizeMod". c.width = 10 * sizeMod; c.height = 10 * sizeMod; for (var x = 0; x < sizeMod; x++) { for (var y = 0; y < sizeMod; y++) { var color = (Math.abs(Math.round(1 + (Math.random() * 3)) * 4 - 1)).toString('16'); color = '#' + color + color + color + color + color + color; ctx.fillStyle = color; ctx.fillRect(x * sizeMod, y * sizeMod, sizeMod, sizeMod); } } var imgd = ctx.getImageData(0, 0, 10 * sizeMod, 10 * sizeMod); var pix = imgd.data; var white_count = 0; for (var p = 0; p < pix.length; p += 4) { var c = { r: pix[p + 0], g: pix[p + 1], b: pix[p + 2], a: pix[p + 3], hex: '#' + pix[p + 0].toString('16') + '' + pix[p + 1].toString('16') + '' + pix[p + 2].toString('16') } if (c.hex == '#ffffff') { white_count++; } } console.log(white_count + "\\nis white\\none tile is", (sizeMod * sizeMod), "big so", white_count / (sizeMod * sizeMod), "tiles") 
 <canvas id="c" width="10" height="10" style="min-width: 100%; min-height: 100%;"> 

jsfiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM