在WebGL上访问图像/纹理数据(纹素)

pio*_*ion 5 webgl

我在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;
Run Code Online (Sandbox Code Playgroud)

我想在加载后获得纹理贴图的内容(RGBA).类似,readPixels()获取绘图缓冲区内容的能力.

可能吗?如果是这样,最好的做法是什么?

我正在使用Chrome Canary build进行开发.

在此先感谢您的帮助.

注:http ://www.khronos.org/message_boards/viewtopic.php?f = 43&t=3439上的交叉发布

nkr*_*ron 9

您可以创建由纹理支持的帧缓冲区,然后使用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;
Run Code Online (Sandbox Code Playgroud)


pio*_*ion 8

我使用HTML5来读取带有以下代码片段的纹素:

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
Run Code Online (Sandbox Code Playgroud)

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