在WebGL中访问图像/纹理数据(texels)

5

我有以下WebGL代码片段:

var texture = gl.createTexture();
texture.image = new Image();
texture.image.onload = function() { 
     .... // I want to read the pixels once the image has been loaded
};
texture.image.src = urlImage;

一旦纹理贴图被加载,我想要获取其内容(RGBA)。类似地,readPixels() 有能力获取绘图缓冲区的内容。是否可能?如果是,最好的方法是什么?我正在使用Chrome Canary版本进行开发。事先感谢您的帮助。
注:在http://www.khronos.org/message_boards/viewtopic.php?f=43&t=3439上发布了交叉帖子。

可能是从WebGL纹理中读取像素的重复问题。 - Leon
2个回答

11
你可以创建一个由纹理支持的framebuffer,然后使用readPixels()获取原始的RGBA数据。
var texture = gl.createTexture();
texture.image = new Image();
texture.image.onload = function() { 

  // Push Texture data to GPU memory
  gl.bindTexture(gl.TEXTURE_2D, texture);
  gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
  gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);

  // Create a framebuffer backed by the texture
  var framebuffer = gl.createFramebuffer();
  gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);

  // Read the contents of the framebuffer (data stores the pixel data)
  var data = new Uint8Array(this.width * this.height * 4);
  gl.readPixels(0, 0, this.width, this.height, gl.RGBA, gl.UNSIGNED_BYTE, data);

  gl.deleteFramebuffer(framebuffer);
};
texture.image.src = urlImage;

9
我使用HTML5以下代码片段读取texels:
```html

我使用HTML5以下代码片段读取texels:

```
var myCanvas = document.createElement("canvas");
myCanvas.width = texture.image.width; 
myCanvas.height = texture.image.height;
var myCanvasContext = myCanvas.getContext("2d"); // Get canvas 2d context
myCanvasContext.drawImage(texture.image, 0, 0); // Draw the texture
var texels = myCanvasContext.getImageData(0,0, width, height); // Read the texels/pixels back

它做了我想做的事情。如果有更好的方法,请告诉我。


这样做可以运行,但由于canvas中2D上下文的工作方式,它无法给您精确的RGB值。在此处进一步解释 http://stackoverflow.com/a/24592348/1289287。 - Billy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接