Uniforms

You may need to read the article about attributes before this one.


Another way to pass data to the GPU is with uniforms, which are variables that are uniform for each vertex. They can be defined in both vertex and fragment shaders.

Uniforms are declared using the uniform keyword. For example:

#version 300 es

precision highp float;

uniform vec4 u_color;

out vec4 outColor;

void main() {
	outColor = u_color;
}

In order to manipulate a uniform from JavaScript, the WebGL API must first be queried for its location with getUniformLocation. For example:

const location: WebGLUniformLocation | null = gl.getUniformLocation(
	program,
	"u_color"
);

A uniform's value can be updated by calling the function that corresponds to the type of data that it holds. For uniforms that hold most types of data, this function is some form of uniform[1234][uif][v]. For matrices, this function is some form of uniformMatrix[234]x[234]fv. For example:

gl.uniform4fv(location, [1, 0, 0, 1]);

The next article is about varyings.