Using drawElements
Unlike the previous case where no IBO was defined, drawElements allows us to use the IBO to tell WebGL how to render the geometry. Remember that drawArrays uses VBOs, which means that the vertex shader will process the repeated vertices as many times as they appear in the VBO. On the other hand, drawElements uses indices. Therefore, vertices are only processed once, and can be used as many times as they are defined in the IBO. This feature reduces both the memory and processing required on the GPU.
Let's revisit the following diagram:
When we use drawElements, we need at least two buffers: a VBO and an IBO. As the vertex shader gets executed on each vertex, the rendering pipeline assembles the geometry into triangles using the IBO.
When using drawElements, you need to make sure that the corresponding IBO is currently bound.
The signature for drawElements is as follows:
gl.drawElements(mode, count, type, offset)
Where:
- mode: Represents the type of primitive we are going to render. The possible values for mode are POINTS, LINE_STRIP, LINE_LOOP, LINES, TRIANGLE_STRIP, TRIANGLE_FAN, and TRIANGLES.
- count: Specifies the number of elements to be rendered.
- type: Specifies the type of the values in indices. Must be UNSIGNED_BYTE or UNSIGNED_SHORT, as we are handling indices (integer numbers).
- offset: Indicates which element in the buffer will be the starting point for rendering. It is usually the first element (zero value).
When drawElements is called, it uses count sequential elements from an enabled array, starting at the offset to construct a sequence of geometric primitives. Mode specifies what kinds of primitives are constructed and how the array elements construct these primitives. If more than one array is enabled, each is used.