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) |
|
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.