We can go now to the offscreen buffer and read the color from the coordinates that we clicked on the canvas.
WebGL allows us to read back from a framebuffer using the readPixels
function. As usual, having gl
as the WebGL context variable:
Function |
Description |
---|---|
|
According to the WebGL specification at the time of writing this book it needs to be of type |
Remember that WebGL works as a state machine and many operations only make sense if this machine is in a valid state. In this case, we need to make sure that the framebuffer from which we want to read, the offscreen framebuffer, is the current one. To do that, we bind it using bindFramebuffer
. Putting everything together, the code looks like this:
//read one pixel var 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 it has one pixel of width times one pixel height times four channels, as the format is RGBA
. You do not need to specify the size this way; we just did it so that it was clear why the size is 4 when we are just retrieving one pixel.
18.119.139.50