我正在尝试使用两个缓冲区渲染两个三角形,我已经看过一些教程并尝试调用 glDrawArrays 函数两次。然而,仅渲染最新的缓冲区数据,即仅渲染一个三角形。请帮助我解决和理解绘制多个对象的概念,提前致谢。
这是代码
// HelloTriangle.js (c) 2012 matsuda
// Vertex shader program
var VSHADER_SOURCE =
'attribute vec4 a_Position;\n' +
'void main() {\n' +
' gl_Position = a_Position;\n' +
'}\n';
// Fragment shader program
var FSHADER_SOURCE =
'void main() {\n' +
' gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n' +
'}\n';
function main() {
// Retrieve <canvas> element
var canvas = document.getElementById('webgl');
// Get the rendering context for WebGL
var gl = getWebGLContext(canvas);
if (!gl) {
console.log('Failed to get the rendering context for WebGL');
return;
}
// Initialize shaders
if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
console.log('Failed to intialize shaders.');
return;
}
// Write the positions of vertices to a vertex shader
var n = initVertexBuffers(gl);
if (n < 0) {
console.log('Failed to set the positions of the vertices');
return;
}
// Specify the color for clearing <canvas>
gl.clearColor(0, 0, 0, 1);
// Clear <canvas>
gl.clear(gl.COLOR_BUFFER_BIT);
// Draw the rectangle
gl.drawArrays(gl.TRIANGLES, 0, n);
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0);
gl.drawArrays(gl.TRIANGLES, 0, n);
}
function initVertexBuffers(gl) {
var vertices = new Float32Array([
0, 0.5, -0.5, -0.5, 0.5, -0.5,
]);
var verticesOne = new Float32Array([
0.5, -0.5, 0, 0.5, 0.5, 2.0
]);
var n = 3; // The number of vertices
// Create a buffer object
var vertexBuffer = gl.createBuffer();
if (!vertexBuffer) {
console.log('Failed to create the buffer object');
return -1;
}
var vertexBufferO = gl.createBuffer();
// Bind the buffer object to target
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
// Write date into the buffer object
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBufferOne);
// Write date into the buffer object
gl.bufferData(gl.ARRAY_BUFFER, verticesOne, gl.STATIC_DRAW);
var a_Position = gl.getAttribLocation(gl.program, 'a_Position');
if (a_Position < 0) {
console.log('Failed to get the storage location of a_Position');
return -1;
}
// Assign the buffer object to a_Position variable
gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0);
// Enable the assignment to a_Position variable
gl.enableVertexAttribArray(a_Position);
return n;
}
Run Code Online (Sandbox Code Playgroud)
WebGL 基本上只有 2 个“真正的”函数。gl.drawArrays几乎gl.drawElements 所有 WebGL API 的其余部分都只是为这两个函数设置状态。
因此,对于您绘制的每件事,您都需要设置所需的所有状态。
for each thing to draw
1. bind buffers and set attributes
2. use program
3. set uniforms and bind texture units
4. call draw
Run Code Online (Sandbox Code Playgroud)
在初始化过程中,您只需执行两次步骤 1。它需要在你绘制那个特定的东西之前发生。