files/en-us/web/api/webglrenderingcontext/readpixels/index.md
{{APIRef("WebGL")}}{{AvailableInWorkers}}
The WebGLRenderingContext.readPixels() method of the WebGL API reads a block of pixels from a
specified rectangle of the current color framebuffer into a {{jsxref("TypedArray")}} or a {{jsxref("DataView")}} object.
// WebGL1:
readPixels(x, y, width, height, format, type, pixels)
// WebGL2:
readPixels(x, y, width, height, format, type, offset)
readPixels(x, y, width, height, format, type, pixels)
readPixels(x, y, width, height, format, type, pixels, dstOffset)
x
y
width
height
format
: A {{domxref("WebGL_API/Types", "GLenum")}} specifying the format of the pixel data. Possible values:
gl.ALPHA
gl.RGB
gl.RGBA
WebGL2 adds
gl.REDgl.RGgl.RED_INTEGERgl.RG_INTEGERgl.RGB_INTEGERgl.RGBA_INTEGERtype
: A {{domxref("WebGL_API/Types", "GLenum")}} specifying the data type of the pixel data. Possible values:
gl.UNSIGNED_BYTEgl.UNSIGNED_SHORT_5_6_5gl.UNSIGNED_SHORT_4_4_4_4gl.UNSIGNED_SHORT_5_5_5_1gl.FLOATWebGL2 adds
gl.BYTEgl.UNSIGNED_INT_2_10_10_10_REVgl.HALF_FLOATgl.SHORTgl.UNSIGNED_SHORTgl.INTgl.UNSIGNED_INTgl.UNSIGNED_INT_10F_11F_11F_REVgl.UNSIGNED_INT_5_9_9_9_REVpixels
type parameter:
gl.UNSIGNED_BYTE.gl.UNSIGNED_SHORT_5_6_5,
gl.UNSIGNED_SHORT_4_4_4_4, or gl.UNSIGNED_SHORT_5_5_5_1.gl.FLOAT.dstOffset {{optional_inline}}
None ({{jsxref("undefined")}}).
A gl.INVALID_ENUM error is thrown if format or
type is not an accepted value.
A gl.INVALID_OPERATION error is thrown if
type is gl.UNSIGNED_SHORT_5_6_5 and
format is not gl.RGB.type is gl.UNSIGNED_SHORT_4_4_4_4 and
format is not gl.RGBA.type does not match the typed array type of pixels.A gl.INVALID_FRAMEBUFFER_OPERATION error is thrown if the currently
bound framebuffer is not framebuffer complete.
const canvas = document.getElementById("canvas");
const gl = canvas.getContext("webgl");
const pixels = new Uint8Array(
gl.drawingBufferWidth * gl.drawingBufferHeight * 4,
);
gl.readPixels(
0,
0,
gl.drawingBufferWidth,
gl.drawingBufferHeight,
gl.RGBA,
gl.UNSIGNED_BYTE,
pixels,
);
console.log(pixels); // Uint8Array
{{Specifications}}
{{Compat}}