javascript WebGL - 从渲染缓冲区读取像素数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6171932/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 19:45:41  来源:igfitidea点击:

WebGL - reading pixel data from render buffer

javascripthtmlimage-processingcanvaswebgl

提问by Sean Kent

Is there a way to get the raw pixel data from a WebGL render buffer or frame buffer that is off screen?

有没有办法从屏幕外的 WebGL 渲染缓冲区或帧缓冲区获取原始像素数据?

I'm using WebGL to do some image processing, e.g. blurring an image, adjusting color, etc. I'm using frame buffers to render to textures at the full image size, then using that texture to display in the viewport at a smaller size. Can I get the pixel data of a buffer or texture so I can work with it in a normal canvas 2d context? Or am I stuck with changing the viewport to the full image size and grabbing the data with canvas.toDataURL()?

我正在使用 WebGL 进行一些图像处理,例如模糊图像、调整颜色等。我正在使用帧缓冲区以完整图像尺寸渲染纹理,然后使用该纹理以较小尺寸显示在视口中. 我可以获取缓冲区或纹理的像素数据,以便在普通画布 2d 上下文中使用它吗?或者我是否坚持将视口更改为完整图像大小并使用 canvas.toDataURL() 获取数据?

Thanks.

谢谢。

采纳答案by to_masz

This is very old question, but I have looked for the same in three.js recently. There is no direct way to render to frame buffer, but actually it is done by render to texture (RTT) process. I check the framework source code and figure out the following code:

这是一个很老的问题,但我最近在three.js 中寻找相同的问题。没有直接渲染到帧缓冲区的方法,但实际上它是通过渲染到纹理 (RTT) 过程完成的。我检查框架源代码并找出以下代码:

renderer.render( rttScene, rttCamera, rttTexture, true );

// ...

var width = rttTexture.width;
var height = rttTexture.height;
var pixels = new Uint8Array(4 * width * height); // be careful - allocate memory only once

// ...

var gl = renderer.context;
var framebuffer = rttTexture.__webglFramebuffer;
gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);        
gl.viewport(0, 0, width, height);
gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);

回答by brainjam

readPixels()should do what you want. Read more in the WebGL spec at http://www.khronos.org/registry/webgl/specs/latest/

readPixels()应该做你想做的。在http://www.khronos.org/registry/webgl/specs/latest/阅读更多 WebGL 规范

回答by user3239667

Yes, you can read raw pixel data. Set preserveDrawingBuffer as true while getting webgl context and afterwards make use of readPixels by WebGL.

是的,您可以读取原始像素数据。在获取 webgl 上下文时将preserveDrawingBuffer 设置为true,然后通过WebGL 使用readPixels。

var context = canvasElement.getContext("webgl", {preserveDrawingBuffer: true}
var pixels = new Uint8Array(4 * width * height);
context.readPixels(x, y, width, height, context.RGBA, context.UNSIGNED_BYTE, pixels)