Getting a pixel in webgl area

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

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

  1. 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);

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

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

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.