我目前正在学习Webgl,在下面的示例中,我对gl.COLOR_BUFFER_BIT的用法有一个令人困惑的点:
const canvas = document.querySelector("#glcanvas");
// Initialize the GL context
const gl = canvas.getContext("webgl");
// Only continue if WebGL is available and working
if (!gl) {
alert("Unable to initialize WebGL. Your browser or machine may not support it.");
return;
}
// Set clear color to black, fully opaque
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT);
console.log('1: ', gl.COLOR_BUFFER_BIT);
// Clear the color buffer with specified clear color
gl.clearColor(1, 1, 1, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT);
console.log('2: ', gl.COLOR_BUFFER_BIT);
Run Code Online (Sandbox Code Playgroud)
我的理解gl.clear(gl.COLOR_BUFFER_BIT)
是将 的值设置gl.COLOR_BUFFER_BIT
为 中设置的颜色gl.clearColor()
。
所以上面两个console.log(gl.COLOR_BUFFER_BIT)
应该输出不同的值。但实际输出如下:
1: 16384
2: 16384
Run Code Online (Sandbox Code Playgroud)
那么这有什么问题吗?
COLOR_BUFFER_BIT
是一个常量,用于告诉clear
要清除的缓冲区,还有DEPTH_BUFFER_BIT
和STENCIL_BUFFER_BIT
,这些值是位掩码,意味着您可以通过对OR
它们进行二进制处理来提供多个“清除目标”,例如,您可以通过调用 来清除颜色和深度缓冲区gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT)
。调用clearColor
设置(只有一个)全局透明颜色,还有clearDepth
和clearStencil
函数设置各自的全局值。
换句话说,clear
实际上使用先前通过方法定义的值来清除给定的目标clear****
,一旦设置,这些值将持续存在,直到您设置另一个值。