Search code examples
javascripttextureswebglshader

Webgl readPixels() invalid operation: invalid format/type combination


Im trying to read the RGBA values of a texture i have but it keeps returning the following error and every value comes out as 0:

WebGL: INVALID_OPERATION: readPixels: invalid format/type combination

Heres my code at initialisation where pixels is an array of texture values:

   texture = gl.createTexture()
   gl.activeTexture(gl.TEXTURE0)
   gl.bindTexture(gl.TEXTURE_2D, texture)
   gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)
   gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, n, n, 0,
     gl.RGBA, gl.FLOAT, new Float32Array(pixels))

   gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST)
   gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)

   FBO = gl.createFramebuffer()

   gl.bindFramebuffer(gl.FRAMEBUFFER, FBO)
   gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0,
       gl.TEXTURE_2D, texture, 0)

And then later on, on a click event i run the following:

gl.bindFramebuffer(gl.FRAMEBUFFER, FBO);

var data = new Uint8Array(resolution * resolution * 4);
gl.readPixels(0, 0, resolution, resolution, gl.RGBA, gl.UNSIGNED_BYTE, data);

console.log(data)

Data returns a large array of zeros. What is the correct combination of format and type or where have i gone wrong here?


Solution

  • After using gl.getContext("experimental-webgl")

    I managed to read the pixels of a float texture using the following:

      gl.bindFramebuffer(gl.FRAMEBUFFER, _this.myFrameBufferObject);
      var data = new Float32Array(resolution * resolution * 4);
      gl.readPixels(0,0,resolution,resolution,gl.RGBA,gl.FLOAT,data);
    

    Credit goes to the comment below this answer