PDA

View Full Version : Getting a pixel in webgl area



yakuzatemplarlol
09-07-2010, 04:35 PM
Hi all,

I know behind webgl is a canvas object. However, when I attemp to use getcontext('2d'), realizing it does not work for webgl canvas. So, how am I going to get the pixel information from a Webgl canvas?

Regards
Dave

gregg
09-16-2010, 02:59 PM
3 options

1) Draw it into 2d canvas

<canvas id="a"></canvas>
<canvas id="b"></canvas>

a = document.getElementById("a");
b = document.getElementById("b");
gl = a.getContext("webgl");
ctx = b.getContext("2d");

gl.clearColor(1,0,0,1);
gl.clear(gl.COLOR_BUFFER_BIT);

ctx.drawImage(a);

// now use ctx to get the pixels

2) Use readPixels

buf = new Uint8Array(gl.canvas.width * gl.canvas.height * 4);
gl.readPixels(0, 0, gl.canvas.width, gl.canvas.height, gl.RGBA, gl.UNSIGNED_BYTE, buf);

3) If all you want is a PNG or JPG canvas.toDataURL still works.

yakuzatemplarlol
10-31-2010, 07:52 PM
Hi Greg,

Hey thanks for your reply. I'll try it out. Nearly lost the hope of getting the answer for this question, thank goodness that I have come back to have a look (after a month)

Regards,
Dave

LordAshes
01-28-2012, 09:30 AM
When using ReadPixel, I found some problems when my Canvas was not square (i.e. when Canvas Width and Height did not match). As soon as they matched (regardless if they were a power of 2) Read Pixel returned good values.

So if you have problems reading back pixel values try making you Canvas size square.