2012-11-29 85 views
6

我有一个WebGLTexture对象。如何获得该纹理的像素(类似于WebGL的readPixels,但是用于纹理)?从WebGL纹理读取像素

我的一个想法是用preserveDrawingBuffer = true创建画布和WebGL上下文,并在此画布上呈现我的纹理,以便它显示2D平面,然后使用readPixels。这种方法合理吗?有没有人有这样的示例代码?

回答

7

您可以尝试将纹理附加到帧缓冲区,然后调用帧缓冲区上的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. 
bool 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); 
} 

对于格式= gl.RGBA的纹理,类型= gl.UNSIGNED_BYTE的CanRead应始终是真的。对于其他格式和类型的canRead可能是错误的。

+0

真是个好主意!谢谢!! :) – Andy

+0

所以,据我所知,这只适用于level = 0的纹理,因为gl.framebufferTexture2D需要level = 0。有没有办法处理非零水平呢? – Andy

+0

你可以在着色器中使用texture2DLod渲染一个特定的级别到另一个纹理的级别0,然后阅读它。 – gman