2012-11-29 122 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