多次调用 drawArrays 保持渲染缓冲区

Calling drawArrays several times keeping render buffer

我正在尝试使用 WebGL 制作类似于赢得单人纸牌的动画。我写了下面的代码来抽多张牌。

const canvas = document.createElement('canvas');
canvas.width = canvas.height = 400;
document.body.appendChild(canvas);

const gl = canvas.getContext('webgl');
const program = gl.createProgram();
const shaderSources = {
    VERTEX_SHADER: `
    precision highp float;
    attribute vec2 aCoord;
    uniform float uOffset;
    void main(void) {
        gl_Position = vec4(aCoord + vec2(uOffset, 0.0), 0.0, 1.0);
    }
    `,
    FRAGMENT_SHADER: `
    precision highp float;
    void main(void) {
        gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
    }
    `
}
for (let i in shaderSources) {
    const shader = gl.createShader(gl[i]);
    gl.shaderSource(shader, shaderSources[i]);
    gl.compileShader(shader);
    gl.attachShader(program, shader);
}
gl.linkProgram(program);
gl.useProgram(program);

const aCoordLocation = gl.getAttribLocation(program, 'aCoord');
const aCoordBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, aCoordBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
    -0.75, -0.25, -0.25, -0.25, -0.25, 0.25,
    -0.75, -0.25, -0.75, 0.25, -0.25, 0.25
]), gl.STATIC_DRAW);
gl.enableVertexAttribArray(aCoordLocation);
gl.bindBuffer(gl.ARRAY_BUFFER, aCoordBuffer);
gl.vertexAttribPointer(aCoordLocation, 2, gl.FLOAT, false, 0, 0);

之后,当我运行下面的代码时,两个红色方块按预期绘制。

gl.uniform1f(gl.getUniformLocation(program, 'uOffset'), 0);
gl.drawArrays(gl.TRIANGLES, 0, 6);

gl.uniform1f(gl.getUniformLocation(program, 'uOffset'), 1);
gl.drawArrays(gl.TRIANGLES, 0, 6);

但是如果一张图因为动画延迟了,只会渲染一个方块(第一个方块消失)。

gl.uniform1f(gl.getUniformLocation(program, 'uOffset'), 0);
gl.drawArrays(gl.TRIANGLES, 0, 6);

setTimeout(() => {
    gl.uniform1f(gl.getUniformLocation(program, 'uOffset'), 1);
    gl.drawArrays(gl.TRIANGLES, 0, 6);
});

有没有办法在drawArray有时间差多次执行时离开render buffer?

WebGLContextAttributes dictionary中设置preserveDrawingBuffer:true,作为第二个参数传递给getContext

https://www.khronos.org/registry/webgl/specs/latest/1.0/#WEBGLCONTEXTATTRIBUTES