Creating a Procedural Grid Using UVs in a Shader (GLSL)
Procedural textures are a powerful way to create patterns without relying on image textures. In this article, we’ll explore how to generate a grid pattern using UV coordinates in a GLSL shader.
Understanding UV Mapping for a Grid
In a typical shader, UV coordinates range from (0,0) to (1,1). To create a grid, we can use the fract() function to repeat a pattern and use step() to define the grid lines.
Shader Code to Create a Grid
precision mediump float;
varying vec2 vUv; // UV coordinates
void main() {
float gridSize = 10.0; // Number of grid cells
float lineWidth = 0.05; // Thickness of grid lines
// Scale UVs to create multiple cells
vec2 grid = fract(vUv * gridSize);
// Create vertical and horizontal lines
float line = step(grid.x, lineWidth) + step(grid.y, lineWidth);
// Display the grid as white lines on a black background
gl_FragColor = vec4(vec3(line), 1.0);
}
How the Code Works
gridSize→ Defines how many cells appear across the UV space.fract(vUv * gridSize)→ Creates repeating UV patterns for the grid.step()→ Defines the width of the grid lines.line = step(grid.x, lineWidth) + step(grid.y, lineWidth);Highlights lines where grid.x or grid.y is close to 0.
Vertex Shader (Basic Pass-through)
precision mediump float;
attribute vec3 position;
attribute vec2 uv;
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
Enhancements & Effects
- Adjustable Grid Size: Change
gridSizedynamically for zoom effects. - Animated Grid: Move the grid by adding time:
vec2 grid = fract(vUv * gridSize + vec2(time, time));
- Colored Grid: Replace
vec3(line)with a mix of two colors:
vec3 gridColor = mix(vec3(0.0, 0.5, 1.0), vec3(1.0, 1.0, 1.0), line); gl_FragColor = vec4(gridColor, 1.0);