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
indexed_quad.html · full logical source
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>
  1. Create four reusable corner vertices

    kf: 1event 0kind: lifecycle

    Create four reusable corner vertices.

    3const vertices = new Float32Array→ 4 corners([
    The quad has four colored corners in one vertex array.
    A rectangle can be represented by four shared vertices.
    State after this keyframeunset → 4 cornersvertices
  2. Create six indices for two triangles

    kf: 2event 1kind: lifecycle

    Create six indices for two triangles.

    9const indices = new Uint16Array→ [0,1,2,0,2,3]([0, 1, 2, 0, 2, 3]);
    The index list describes two triangles using shared corners.
    Six indices draw two triangles from four vertices.
    State after this keyframeunset → [0,1,2,0,2,3]indices
  3. Bind the index buffer target

    kf: 3event 2kind: lifecycle

    Bind the index buffer target.

    10gl.bindBuffer→ indexBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
    The element-array target is ready for index data.
    drawElements reads indices from the bound ELEMENT_ARRAY_BUFFER.
    State after this keyframenone → indexBufferindex target
  4. Upload the index array

    kf: 4event 3kind: lifecycle

    Upload the index array.

    11gl.bufferData→ 6 unsigned shorts(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);
    The GPU has the index list for the two triangles.
    Index data is uploaded separately from vertex attributes.
    State after this keyframeempty → 6 unsigned shortsindex buffer
  5. Draw the indexed rectangle

    kf: 5event 4kind: lifecycle

    Draw the indexed rectangle.

    12gl.drawElements→ colored quad(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0);
    A colored rectangle appears, made from two indexed triangles.
    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.