Search code examples
javascriptcanvaspixelgetimagedata

get pixel colour in javascript


This might be a very basic question but as I am a newbie when it comes to javascript I can't figure out the right way to solve my issue. I need to do an if statement which checks the pixel colour and if it's black - do something if it's not - do something else. (It's a back-propagation project so that's why there are iterations)

for(i=1;i<iterations;i++) {
for(j=1;j<300;i+=2) { //canvas size is 300x300
for(k=1;k<300;i+=2) {
if (context.getImageData(j,k,1,1).data == [0, 0, 0, 0])
{/*code to be executed*/}
else {/*other code*/}
}
}
}

Sorry for asking easy stuff but I have not much time to do this so can't start from basics right now.


Solution

  • You need to compare each items in the array:

    var pixel = context.getImageData(j,k,1,1).data; // cache array
    if (pixel[0] === 0 &&                           // R
        pixel[1] === 0 &&                           // G
        pixel[2] === 0 &&                           // B
        pixel[3] === 0) {                           // A
    
        ...
    }
    

    Better yet, not use getImageData() for each pixel but cache it before starting the iterations:

    var x, y,
        buffer = context.getImageData(0, 0, 300, 300).data;
    
    for(y = 0; i < 300; y++) {
        for(x = 0; x < 300; x++) {
            var pos = (y * 300 + x) * 4;
            if (buffer[pos]   === 0 &&               // R
                buffer[pos+1] === 0 &&               // G
                buffer[pos+2] === 0 &&               // B
                buffer[pos+3] === 0) {               // A
    
                ...was black...
            }
            else {
                ...was not black...
            }
       }
    }