Game Development Reference
In-Depth Information
Drawing using index buffer objects
Open the 01-SquareWithDrawIndexArrays.html file in your favorite text editor,
which has the following code:
function initBuffers() {
vertexPositionBuffer = gl.createBuffer();
indexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexPositionBuffer);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
vertices = [
1.0, 1.0, 0.0, //v0
-1.0, 1.0, 0.0, //v1
1.0, -1.0, 0.0, //v2
-1.0, -1.0, 0.0 //v3
];
indices = [0,2,3,0,3,1];
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices),
gl.STATIC_DRAW);
vertexPositionBuffer.itemSize = 3;
vertexPositionBuffer.numItems = 4;
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices),
gl.STATIC_DRAW);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
}
In this code, we change the initBuffer() function to create index buffers. First,
we initialize our array of indices and then create a new buffer of type gl.ELEMENT_
ARRAY_BUFFER, ; we then allocate memory for it using the bufferData() function.
The process is shown in the following code snippet:
function drawScene() {
gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
mat4.perspective(40, gl.viewportWidth / gl.viewportHeight, 0.1,
1000.0, pMatrix);
mat4.identity(mvMatrix);
mat4.translate(mvMatrix, [0.0, 0.0, -7.0]);
gl.bindBuffer(gl.ARRAY_BUFFER, vertexPositionBuffer);
gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute,
vertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0);
 
Search WWH ::




Custom Search