I have the following code snippet on 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;
I want to obtain the contents (RGBA) of the texture map once it has been loaded. Similar, capability of readPixels() to obtain the contents of the drawing buffer.
Is it possible? If so, what's the best to do it?
I am using Chrome Canary build for my development.
Thanks in advance for your help.
Note: Cross post on http://www.khronos.org/message_boards/viewtopic.php?f=43&t=3439
You can create a framebuffer backed by the texture and then use readPixels() to get the raw RGBA data.
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;
I use HTML5 to read the texels with the following code snippets:
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
It does what I want to do. Please let me know if there is a better way
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With