Creating a Rectangle Using UVs in a Shader (GLSL)
In GLSL, you can create a rectangle purely using UV coordinates in a fragment shader. This is useful for procedural texture generation, stylized effects, and more.
Understanding UV Coordinates
UV coordinates in GLSL range from (0,0) in the bottom-left to (1,1) in the top-right. Using these coordinates, we can define a rectangular shape by checking if the fragment lies within a certain range.
Shader Code to Draw a Rectangle
precision mediump float;
varying vec2 vUv; // Interpolated UV from vertex shader
void main() {
// Define rectangle bounds (values between 0 and 1)
vec2 rectMin = vec2(0.3, 0.3); // Bottom-left corner of the rectangle
vec2 rectMax = vec2(0.7, 0.7); // Top-right corner of the rectangle
// Check if UV coordinates fall inside the rectangle
if (vUv.x > rectMin.x && vUv.x < rectMax.x &&
vUv.y > rectMin.y && vUv.y < rectMax.y) {
gl_FragColor = vec4(0.0, 1.0, 1.0, 1.0); // Cyan rectangle
} else {
gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0); // Black background
}
}
Breaking Down the Code
vec2 rectMin&vec2 rectMax→ Define the lower-left and upper-right corners of the rectangle.ifcondition → Checks whether the current fragment’s UV coordinates fall inside the rectangle.- Inside the rectangle → Assigns a cyan color
(0.0, 1.0, 1.0, 1.0). - Outside the rectangle → Assigns a black color
(0.0, 0.0, 0.0, 1.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);
}
- Passes UV coordinates to the fragment shader.
- Transforms the vertex position for rendering.
Modifications & Effects
- Change Rectangle Size: Modify
rectMinandrectMaxvalues. - Soft Edges: Use
smoothstep()for anti-aliased borders. - Animated Rectangle: Modify
rectMinandrectMaxovertime.