readPixels on framebuffer problem

i’m working on my colorpicking implementation and don’t know where i’m mistaken.
It works fine as long as i render to the default framebuffer.

function clickHandler(e){
  var x = e.clientX - gl.canvas.offsetLeft;
  var y = e.clientY - gl.canvas.offsetTop;
  var pixels = new Uint8Array(4);
  gl.bindFramebuffer(gl.FRAMEBUFFER, gl.pickFBuffer);
  gl.readPixels(x, gl.canvas.height - y, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
  gl.bindFramebuffer(gl.FRAMEBUFFER, null);

Like this i get “” as output. If i don’t bind the gl.pickFBuffer, i get the right values, but it flickers shortly.
Here the initialisation of the gl.pickFBuffer:

gl.pickRBuffer = gl.createRenderbuffer();
  gl.pickFBuffer = gl.createFramebuffer();
  gl.pickTexture = gl.createTexture();
  gl.bindTexture(gl.TEXTURE_2D, gl.pickTexture);
  gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.canvas.width, gl.canvas.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  gl.bindFramebuffer(gl.FRAMEBUFFER, gl.pickFBuffer);
  gl.bindRenderbuffer(gl.RENDERBUFFER, gl.pickRBuffer);
  gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, gl.canvas.width, gl.canvas.height);
  gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, gl.pickTexture, 0);
  gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, gl.pickRBuffer);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  if(gl.checkFramebufferStatus(gl.FRAMEBUFFER) != gl.FRAMEBUFFER_COMPLETE)
    alert("Framebuffer incomplete!");
  gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  gl.bindFramebuffer(gl.FRAMEBUFFER, null);

Hope you can help me.

I solved the problem.
Textures need 2^n * 2^m size.
So i tried 2048*1024 texture(and renderbuffer) resolution and it worked. :smiley:

PS: Lower resolutions work too, if you decrease the viewport, so it fits on the texture, and adjust the click coordinates.

I also found that I don’t get proper results from ReadPixel if my framebuffer is trying to match a Canvas that is not square. It seems to work with any Canvas size (doesn’t need to be a power of 2) but as soon as I make the Canvas non-square then I seem to get problems reading back the PixelColor.