Drawing State
Indexed Quad
Four corner vertices and six indices draw a rectangle as two triangles without duplicating shared corners.
Program
Many meshes reuse vertices. An element array buffer stores indices so drawElements can assemble triangles from shared vertex data.
indexed_quad.html
Visuals: generated teaching cards from captured state
- state written by this keyframe
1<canvas id="stage" width="360" height="210"></canvas>
2<script>
3 const vertices = new Float32Array([
4 -0.62, 0.45, 0.96, 0.46, 0.24,
5 -0.62, -0.45, 0.23, 0.75, 0.54,
6 0.62, -0.45, 0.28, 0.48, 0.95,
7 0.62, 0.45, 0.98, 0.78, 0.27
8 ]);
9 const indices = new Uint16Array([0, 1, 2, 0, 2, 3]);
10 gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
11 gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);
12 gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0);
13</script>Create four reusable corner vertices
kf: 1event 0kind: lifecycleCreate four reusable corner vertices.
3const vertices = new Float32Array→ 4 corners([
A rectangle can be represented by four shared vertices. State after this keyframeunset → 4 cornersverticesCreate six indices for two triangles
kf: 2event 1kind: lifecycleCreate six indices for two triangles.
9const indices = new Uint16Array→ [0,1,2,0,2,3]([0, 1, 2, 0, 2, 3]);
Six indices draw two triangles from four vertices. State after this keyframeunset → [0,1,2,0,2,3]indicesBind the index buffer target
kf: 3event 2kind: lifecycleBind the index buffer target.
10gl.bindBuffer→ indexBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
drawElements reads indices from the bound ELEMENT_ARRAY_BUFFER. State after this keyframenone → indexBufferindex targetUpload the index array
kf: 4event 3kind: lifecycleUpload the index array.
11gl.bufferData→ 6 unsigned shorts(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);
Index data is uploaded separately from vertex attributes. State after this keyframeempty → 6 unsigned shortsindex bufferDraw the indexed rectangle
kf: 5event 4kind: lifecycleDraw the indexed rectangle.
12gl.drawElements→ colored quad(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0);
drawElements reuses vertex data through the index buffer. State after this keyframeclear color → colored quadpixels
index buffer
An index buffer stores integer vertex references for drawElements.
drawElements
drawElements assembles primitives by looking up vertices through the index buffer.
mesh reuse
Indexed drawing avoids duplicating shared vertex attributes.