Creating a Circular Mask Using UVs in a Shader (GLSL)

Creating a Circular Mask Using UVs in a Shader (GLSL)

In GLSL, you can use UV coordinates to create a circular mask. This technique is useful for procedural textures, vignette effects, and stylized visuals.

Understanding UV Coordinates

UV coordinates range from (0,0) in the bottom-left to (1,1) in the top-right. To create a circle, we need to calculate the distance from the center of the UV space and apply a cutoff.

Shader Code to Draw a Circle

precision mediump float;

varying vec2 vUv; // UV coordinates

void main() {
    vec2 center = vec2(0.5, 0.5); // Center of the circle
    float radius = 0.3; // Radius of the circle

    // Calculate distance from center
    float dist = distance(vUv, center);

    // If within radius, show white; otherwise, make it black
    if (dist < radius) {
        gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0); // White circle
    } else {
        gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0); // Black background
    }
}

Breaking Down the Code

  • vec2 center → Defines the circle’s center in UV space.
  • float radius → Determines the circle’s size.
  • distance(vUv, center) → Calculates the distance from the current fragment to the center.
  • If condition → Colors fragments inside the radius white, and others black.

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.
  • Handles vertex transformations.

Enhancements & Effects

  1. Soft Edges: Use smoothstep() for an anti-aliased border:
float edge = smoothstep(radius - 0.01, radius + 0.01, dist);
gl_FragColor = vec4(vec3(1.0 - edge), 1.0);
  1. Animated Circle: Change radius over time for a pulsing effect.
  2. Gradient Fill: Mix colors based on dist to create a glowing effect.

Leave a comment

Your email address will not be published. Required fields are marked *