我不明白为什么我会在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,为什么会有黑色清除?
答案 0 :(得分: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>