Reading pixels from the offscreen framebuffer

We can go now to the offscreen buffer and read the color from the coordinates that we clicked on the canvas.

Reading pixels from the offscreen framebuffer

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

Function

Description

gl.readPixels(x, y, width, height, format, type, pixels)

x and y: Starting coordinates.

width, 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: At the time of writing this book the only supported format is gl.RGBA.

type: At the time of writing this book the only supported type is gl.UNSIGNED_BYTE.

pixels: It is 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).

According to the WebGL specification at the time of writing this book it needs to be of type Uint8Array.

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

Note

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.139.50