【问题标题】:Read pixels from a WebGL texture从 WebGL 纹理中读取像素
【发布时间】:2012-11-17 13:48:18
【问题描述】:

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

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

【问题讨论】:

    标签: textures webgl


    【解决方案1】:

    您可以尝试将纹理附加到帧缓冲区,然后在帧缓冲区上调用 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 的纹理,type = gl.UNSIGNED_BYTE canRead 应该始终为真。对于其他格式和类型,canRead 可能为 false。

    【讨论】:

    • 所以,据我了解,这仅适用于 level=0 的纹理,因为 gl.framebufferTexture2D 需要 level=0。有没有办法处理非零级别?
    • 您可以在着色器中使用 texture2DLod 将特定级别渲染到另一个纹理的级别 0,然后读取。
    • 这似乎不适用于非无符号字节的纹理。
    • @matth 它似乎适用于我的计算机上的浮点通道纹理,最新版本的 Chrome。
    • 看到标签是“webgl”我想这是JS,bool canRead应该是var canReadlet canRead,但不是bool。 ;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-05
    • 1970-01-01
    • 1970-01-01
    • 2017-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多