As I understand it: ctx.readPixels takes the following arguments: x is the starting index horizontally, y is the starting index vertically, ax is the number of columns starting at index x, ay is the number of rows starting at index y, format is the way to fill the array (gl.RGBA mainly), type - variable type (gl.UNSIGNED_BYTE basically), callbackArr - returned array (Uint8Array type array, the number of cells that is equal to ax * ay).

If everything is correct, then I cannot understand why with this canvas:

Webgl

with a width of 1920 and a height of 1024, specifying the readPixels function (0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, arr), the array arr == [255,255,255,255] is returned (everything is correct), and with this canvas:

Webgl

and with the same width and height, and the same function arguments, the same array is obtained, although it can be seen from the figure that the 1st pixel has changed color to 255, 0, 0, 255? Thanks in advance for the answer

  • The problem was that the counting of coordinates in the canvas, and in this case using the readPixels method comes from the bottom left corner. That is, if you put a red figure in the 2nd figure in the lower left corner, you will get the expected 255, 0, 0, 255. - Vyacheslav

1 answer 1

The size of the array should be x * y * 4 whose element size is 8 bits. Try glReadBuffer (GL_FRONT); or GL_BLACK

In general, you hike 1 element just read and not 4. Straighten the size of the array.

  • So I read 1 element, * 4 - this is rgba, different colors = 1 array element. - Vyacheslav
  • You have an 8 bit array element. RGBA is 4 times 8 bits. 0 element = R 1 element = G, etc. - Alexey Malchenko