Drawing many shapes in WebGL

In pseudo code

At init time

  • Get a context (gl) from the canvas element.
  • for each shader
    • create shader
    • look up attribute and uniform locations
  • for each shape
    • initialize buffers with the shape
  • for each texture
    • create textures and/or fill them with data.

At draw time

  • for each shape
    • if the last shader used is different than the shader needed for this shape call gl.useProgram
    • For each attribute needed by shader
      • call gl.enableVertexAttribArray, gl.bindBuffer and gl.vertexAttribPointer for each attribute needed by shape with the attribute locations for the current shader.
    • For each uniform needed by shader
      • call gl.uniformXXX with the desired values using the locations for the current shader
    • call gl.drawArrays or if the data is indexed called gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, bufferOfIndicesForCurrentShape) followed by gl.drawElements

Common Optimizations

1) Often you don’t need to set every uniform. For example if you are drawing 10 shapes with the same shader and that shader takes a viewMatrix or cameraMatrix it’s likely that viewMatrix uniform or cameraMatrix uniform is the same for every shape so just set it once.

2) You can often move the calls to gl.enableVertexAttribArray to initialization time.

Leave a Comment