WebGLRenderingContext:readPixels() 方法
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.
备注: 此特性在 Web Worker 中可用。
WebGL API 的 WebGLRenderingContext.readPixels() 方法从当前的颜色帧缓冲(framebuffer)中读取指定矩形的像素矩阵并转换为 TypedArray 或 DataView 对象。
语法
js
// 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-
GLint值,指定从矩形像素块的左下角读取的第一个水平像素。 y-
GLint值,指定从矩形像素块的左下角读取的第一个垂直像素。 width-
GLsizei值,指定矩形的宽度。 height-
GLsizei值,指定矩形的高度。 format-
GLenum值,指定像素数据的格式,可能的值有:gl.ALPHA-
放弃红、绿、蓝通道读取 alpha 通道的数据。
gl.RGB-
放弃 alpha 通道,读取红、绿、蓝通道的数据。
gl.RGBA-
从颜色缓存区读取红、绿、蓝以及 alpha 通道的数据。
WebGL2 增加的
gl.REDgl.RGgl.RED_INTEGERgl.RG_INTEGERgl.RGB_INTEGERgl.RGBA_INTEGER
type-
GLenum值,指定像素数据的数据类型,可能的值有:gl.UNSIGNED_BYTEgl.UNSIGNED_SHORT_5_6_5gl.UNSIGNED_SHORT_4_4_4_4gl.UNSIGNED_SHORT_5_5_5_1gl.FLOAT
WebGL2 增加的
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_REV
pixels-
用于读取数据的对象,必须与参数
type的类型相匹配:Uint8Array:gl.UNSIGNED_BYTE。Uint16Array:gl.UNSIGNED_SHORT_5_6_5、gl.UNSIGNED_SHORT_4_4_4_4或gl.UNSIGNED_SHORT_5_5_5_1。Float32Array:gl.FLOAT。
dstOffset可选-
偏移量,默认为 0。
返回值
无(undefined)。
异常
-
gl.INVALID_ENUM:如果format或type不是可接受的值,则会引发此错误。 -
gl.INVALID_OPERATION:抛出此错误可能的原因:type是gl.UNSIGNED_SHORT_5_6_5且format不是gl.RGB。type是gl.UNSIGNED_SHORT_4_4_4_4且format不是gl.RGBA。type与类型化数组pixels的类型不匹配。
-
gl.INVALID_FRAMEBUFFER_OPERATION:如果当前绑定的帧缓冲区未完成,则引发此错误。
示例
js
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
规范
| Specification |
|---|
| WebGL Specification> # 5.14.12> |
浏览器兼容性
Loading…