【问题标题】:requestAnimationFrame , readpixel and implicit clearrequestAnimationFrame , readpixel 和隐式清除
【发布时间】:2019-03-02 00:16:06
【问题描述】:

我不明白为什么我在 requestanimationframe 循环中丢失了 readpixel 值?

var pixels = new Uint8Array(12*12*4); 

gl.clearColor(0.5, 0.8, 0.0, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT);
gl.readPixels(0, 0, 12, 12, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
console.log(pixels[0]);  //OK 128 !
anim();


function anim() {

  var pixels2 = new Uint8Array(12*12*4); 

  gl.readPixels(0, 0, 12, 12, gl.RGBA, gl.UNSIGNED_BYTE, pixels2);
  console.log(pixels2[0]); // STRANGE : 0 ????
  requestAnimationFrame(anim);
}

显然,如果我添加

gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT);

在 anim() {...} 里面,值是 128。但是没有那个 gl.clear,为什么会有一个黑色的 clear ?

【问题讨论】:

    标签: javascript webgl


    【解决方案1】:

    因为默认情况下 WebGL 在每次复合操作后都会清除绘图缓冲区。见https://stackoverflow.com/a/26790802/128511

    如果您不希望 WebGL 清除绘图缓冲区,则需要将 preserveDrawingBuffer: true 传递给 getContext

    const gl = document.querySelector('canvas')
      .getContext('webgl', {preserveDrawingBuffer: true});
    var pixels = new Uint8Array(12*12*4); 
    
    gl.clearColor(0.5, 0.8, 0.0, 1.0);
    gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT);
    gl.readPixels(0, 0, 12, 12, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
    console.log(pixels[0]);  //OK 128 !
    anim();
    
    
    function anim() {
    
      var pixels2 = new Uint8Array(12*12*4); 
    
      gl.readPixels(0, 0, 12, 12, gl.RGBA, gl.UNSIGNED_BYTE, pixels2);
      console.log(pixels2[0]); // STRANGE : 0 ????
      requestAnimationFrame(anim);
    }
    <canvas></canvas>

    【讨论】:

    • 哦...好吧!我正在寻找 requestanimationframe 规范。这是一种 webgl 行为。谢谢!
    猜你喜欢
    • 2019-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-13
    • 2013-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多