webgl buffer and attribute pointer

buffer

Vertex attributes are read from arrays of binary data called buffers.

  1. gl.createBuffer() To create a buffer
  2. gl.bindBuffer(gl.ARRAY_BUFFER, buffer) bind and define the buffer target type
  3. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(DATA), gl.DYNAMIC_DRAW) set the buffer data
const buffer = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, buffer)
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(DATA), gl.DYNAMIC_DRAW)

gl.bindBuffer(target: GLenum, buffer: WebGLBuffer)1

target: GLenum

buffer: WebGLBuffer

gl.bufferData(target: GLenum, data: [], usageHint:)2

target: GLenum
data: is either a number representing the size of the buffer to reserve, or a typed array representing data to allocate.
usageHint is a flag which has no semantic effect, but can be one of the following values, used for performance hints.

// WebGL1:
void gl.bufferData(target, size, usage);
void gl.bufferData(target, ArrayBuffer? srcData, usage);
void gl.bufferData(target, ArrayBufferView srcData, usage);

// WebGL2:
void gl.bufferData(target, ArrayBufferView srcData, usage, srcOffset, length);

attribute pointers

vertex attribute pointers are pointers to the buffer data, to define the range of data from buffer.

const VERT_SRC = `
    attribute vec2 position;
    voind main() {
        vec2 pos = position
        gl_Position = vec4(pos, 0, 1)
    }
`
const BUFFER_DATA = [
    x0, y0,
    x1, y1,
    x2, y2
]
let program
// program = createShaderProgram()

const positionLocation = 0 // defined the location of the attribute

const buffer = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, buffer)
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(BUFFER_DATA), gl.DYNAMIC_DRAW)

gl.bindAttribLocation(program, positionLocation, 'position')
gl.enableVertexAttribArray(positionLocation)
gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0)

Footnotes

  1. MDN - WebGLRenderingContext.bindBuffer()

  2. MDN - WebGLRenderingContext.bufferData()