Reading Pixels from the Offscreen Framebuffer

We can now go to the offscreen buffer and read the color from the appropriate coordinates:

WebGL allows us to read back from a framebuffer using the readPixels function. As usual, having gl as the WebGL context variable within our context:

Function Description
gl.readPixels(x, y, width, height, format, type, pixels)
  • x and y: Starting coordinates.
  • width and height: The extent of pixels to read from the framebuffer. In our example, we are just reading one pixel (where the user clicks), so this will be 1, 1.
  • format: Supports the gl.RGBA format.
  • type:: Supports the gl.UNSIGNED_BYTE type.
  • pixels: A typed array that will contain the results of querying the framebuffer. It needs to have sufficient space to store the results depending on the extent of the query (x, y, width, height). It supports the Uint8Array type.

Remember that WebGL works as a state machine; thus, many operations depend on the validity of its state. In this case, we need to ensure that the offscreen framebuffer that we want to read from is the currently bound one. To do so, we bind it by using bindFramebuffer. Putting everything together, the code looks like this:

// read one pixel
const readout = new Uint8Array(1 * 1 * 4);
gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
gl.readPixels(coords.x, coords.y, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, readout);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);

Here, the size of the readout array is 1 * 1 * 4. This means that it has one pixel of width times one pixel height times four channels, since the format is RGBA. You do not need to specify the size this way; this was done to demonstrate why the size is 4 when we are just retrieving one pixel.