我有一个 WebGLTexture 对象。我如何获取该纹理的像素(类似于 WebGL 的 readPixels,但用于纹理)?
我的一个想法是创建一个画布和一个带有 preserveDrawingBuffer=true 的 WebGL 上下文,并在这个画布上渲染我的纹理,以便它显示 2D 平面,然后使用 readPixels。这种做法合理吗?有人有这方面的示例代码吗?
您可以尝试将纹理附加到帧缓冲区,然后在帧缓冲区上调用 readPixels。
在初始时间
// make a framebuffer
fb = gl.createFramebuffer();
// make this the current frame buffer
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
// attach the texture to the framebuffer.
gl.framebufferTexture2D(
gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0,
gl.TEXTURE_2D, texture, 0);
// check if you can read from this type of texture.
let canRead = (gl.checkFramebufferStatus(gl.FRAMEBUFFER) == gl.FRAMEBUFFER_COMPLETE);
// Unbind the framebuffer
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
在阅读时
if (canRead) {
// bind the framebuffer
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
// read the pixels
gl.readPixels(......);
// Unbind the framebuffer
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
}
对于 format = gl.RGBA 的纹理,type = gl.UNSIGNED_BYTE canRead 应该始终为真。对于其他格式和类型,canRead 可能是错误的。