如何使用gl.readPixels读取点大小> 1的绘制的gl.POINTS?

时间:2019-12-09 10:51:02

标签: javascript glsl webgl

我的目标是读取画布上较大点的像素。目前,我什至无法获得在pointSize = 1处绘制的像素。这是一个链接:https://codepen.io/issabln/pen/LYEGWyO

代码段:

function drawOneBlackPixel( gl, x, y ) {
    // Fills the buffer with a single point?
    gl.bufferData( gl.ARRAY_BUFFER, new Float32Array([
      x,     y]), gl.STATIC_DRAW );

    // Draw one point.
    gl.drawArrays( gl.POINTS, 0, 1 );
}

gl.clearColor(1.0, 1.0, 1.0, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT);

// These tests are supposed to be x,y coordinates from top left.
drawOneBlackPixel( gl, 1, 0 );

const pix = new Uint8Array(4);
gl.readPixels(1, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pix);
console.log(pix)

有什么主意吗?

2 个答案:

答案 0 :(得分:3)

翻转Y坐标就可以了(注意-1,否则您将在视口之外阅读)

gl.readPixels(1, gl.drawingBufferHeight-1, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pix);

答案 1 :(得分:1)

让我们尝试一下

const gl = document.querySelector('canvas').getContext('webgl');
const vs = `
attribute vec4 position;
void main() {
  gl_Position = position;
  gl_PointSize = 1.0;
}
`;
const fs = `
precision mediump float;
uniform vec4 color;
void main() {
  gl_FragColor = color;
}
`;

const prg = twgl.createProgram(gl, [vs, fs]);
gl.useProgram(prg);
const posLoc = gl.getAttribLocation(prg, 'position');
const colorLoc = gl.getUniformLocation(prg, 'color');

function drawPixel(gl, px, py, color) {
  // compute center of pixel in clip space
  const clipX = (px + 0.5) / gl.canvas.width  * 2 - 1;
  const clipY = (py + 0.5) / gl.canvas.height * 2 - 1;
  gl.vertexAttrib2f(posLoc, clipX, clipY);
  gl.uniform4fv(colorLoc, color);
  gl.drawArrays(gl.POINTS, 0, 1);
}

function checkPixel(gl, px, py, expected, msg) {
  const pixel = new Uint8Array(4);
  gl.readPixels(px, py, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
  const actual = Array.from(pixel).map(v => v / 255);
  let same = true;
  for (let i = 0; same && i < 4; ++i) {
    same = actual[i] === expected[i];
  }
  if (same) {
    console.log(`pass: ${px},${py} was ${ actual.join(',')}`);
  } else {
    console.error(`fail: ${px},${py} was ${actual.join(',')} expected ${expected.join(',')}`);
  }
}

drawPixel(gl, 0, 0, [1, 0, 0, 1]);
drawPixel(gl, 299, 0, [0, 1, 0, 1]);
drawPixel(gl, 0, 149, [0, 0, 1, 1]);
drawPixel(gl, 299, 149, [0, 1, 1, 1]);

checkPixel(gl, 0, 0, [1, 0, 0, 1]);
checkPixel(gl, 299, 0, [0, 1, 0, 1]);
checkPixel(gl, 0, 149, [0, 0, 1, 1]);
checkPixel(gl, 299, 149, [0, 1, 1, 1]);
body { background: #444; }
<script src="https://twgljs.org/dist/4.x/twgl.min.js"></script>
<canvas></canvas>