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

时间:2016-12-06 17:31:06

标签: javascript glsl webgl

我正在尝试制作动画,就像使用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多次执行时间差时,有没有办法离开渲染缓冲区?

1 个答案:

答案 0 :(得分:0)

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

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