WebGL Uniforms

If you look at the shaders in the previous section, you see only hardcoded values, with no way to change anything, other than changing and recompiling the shaders source code.

Uniform provide a way to pass values to a linked program from the API. They are like global variables accessible from vertex and frament shaders. Uniforms cannot be changed during a draw call.

// vertex.glsl:
#version 300 es

// these will be set from the API:
uniform vec2 uPosition;         // vec2(x, y)
uniform float uPointSize;       // in pixels

void main() {
    gl_Position = vec4(uPosition, 0.0, 1.0);
    gl_PointSize = uPointSize;
// webgl.js:
const uPosition = gl.getUniformLocation(program, 'uPosition');
const uPointSize = gl.getUniformLocation(program, 'uPointSize');
// do check for null!

gl.uniform1f(uPointSize, 100.0);
gl.uniform2f(uPosition, 0.2, -0.2);
gl.uniform2fv(uPosition, [0.2, -0.2]); // same

GLSL types

typeCan be set via
floatgl.uniform1f(p, a)
vec2gl.uniform2f(p, a, b)
gl.uniform2fv(p, [a, b])
vec3gl.uniform3f(p, a, b, c)
gl.uniform3fv(p, [a, b, c])
vec4gl.uniform4f(p, a, b, c, d)
gl.uniform4fv(p, [a, b, c, d])
typeCan be set via
intgl.uniform1i(p, a)
ivec2gl.uniform2i(p, a, b)
gl.uniform2iv(p, [a, b])
ivec3gl.uniform3i(p, a, b, c)
gl.uniform3iv(p, [a, b, c])
ivec4gl.uniform4i(p, a, b, c, d)
gl.uniform4iv(p, [a, b, c, d])
typeCan be set via
uintgl.uniform1u(p, a)
uvec2gl.uniform2u(p, a, b)
gl.uniform2uv(p, [a, b])
uvec3gl.uniform3u(p, a, b, c)
gl.uniform3uv(p, [a, b, c])
uvec4gl.uniform4u(p, a, b, c, d)
gl.uniform4uv(p, [a, b, c, d])
typeCan be set via
mat2gl.uniformMatrix2fv(p, [a11, a12, a21, a22])
mat3gl.uniformMatrix3fv(p, [a11, a12, a13, ..., a33])
mat4gl.uniformMatrix4fv(p, [a11, a12, a13, ..., a44])

uniformNTv() can set arrays of values, not just one vec2/vec3/ivec2/etc:

// fragment.glsl
uniform vec4 uColors[3];
const uColors = gl.getUniformLocation(program, 'uColors');
gl.uniform4fv(uColors, [
    1.0, 0.0, 0.0, 1.0,  // red
    0.0, 1.0, 0.0, 1.0,  // green
    0.0, 0.0, 1.0, 1.0,  // blue


This is a WebGL uniform demo that translates mouse wheel and click events into changing uPointSize and uPosition uniforms in WebGL: