Search code examples
javascriptcanvasgetimagedata

Filling canvas with fillRect() and getting color of each pixel returns array with 4 zeros


To be straight, I made two canvases, which are filled with part of the JSFiddle logo. The problem is that whenever I want to get color of each pixel with getImageData().data, it returns an empty array meaning the pixel is transparent, what is not true. The problem code:

for (i = 0; i < h; i+=scale)
    for (j = 0; j < w; j+=scale) {
        rgba1 = sctx.getImageData(i,j,1,1).data;
        rgba2 = sctx2.getImageData(i,j,1,1).data;
        // logging
        log('x:'+i/5+' | y:'+j/scale+' | '+rgba1);
        log('x:'+i/scale+' | y:'+j/scale+' | '+rgba2,true);
    }

Printed result:

result

What's the problem with the code? Fiddle here


Solution

  • Take a closer look at your output. Your canvas has a landscape orientation, your coordinates indicate portrait mode.

    for (i = 0; i < w; i+=scale)
        for (j = 0; j < h; j+=scale) {