GLSL built-in function
clamp()
Limits x to the range between minVal and maxVal, computed as min(max(x, minVal), maxVal).
Syntax
float clamp(float x, float minVal, float maxVal)
vec2 clamp(vec2 x, float minVal, float maxVal)
vec3 clamp(vec3 x, float minVal, float maxVal)
vec3 clamp(vec3 x, vec3 minVal, vec3 maxVal)Parameters
- x
- The value to limit.
- minVal
- The lower bound. Values below it become minVal.
- maxVal
- The upper bound. Values above it become maxVal. Must be greater than or equal to minVal.
Return value
x if it is inside the range, otherwise the nearest bound.
Live example
Edit the code and the preview updates as you type.
How it works
clamp(x, minVal, maxVal) keeps x inside a range:
- below
minVal: returnsminVal - above
maxVal: returnsmaxVal - in between: returns x unchanged
In the example the gray diagonal line is the raw value. The green line follows it in the middle and goes flat at the top and bottom, where the value hits the limits. The limits breathe with u_time.
Typical uses
- Keeping colors valid:
clamp(color, 0.0, 1.0)before writing togl_FragColor. - Safe input to other functions:
sqrt(clamp(x, 0.0, 1.0))oracos(clamp(d, -1.0, 1.0))avoid undefined results from out-of-range input. - Hard-edged progress bars:
clamp((u_time - start) / duration, 0.0, 1.0)goes from 0 to 1 and then stays at 1.
Common mistakes
- Swapping the bounds. If
minValis greater thanmaxValthe result is undefined in GLSL and differs between GPUs. - Expecting a smooth transition.
clamphas sharp corners at both ends; usesmoothstepwhen you want an eased curve.
Related functions
Tutorials that use clamp()
- Clamp DemoUse clamp() to keep values in range.
- Diagonal GradientCombine vUv.x and vUv.y to create a diagonal gradient and interpolate colors with mix.
- Rectangle BorderCreate a border by subtracting an inner rectangle mask from an outer one.
- Clamp & SaturatePractice core GLSL math building blocks used across shaders.
- Smooth MinBlend two circle SDFs into one smooth shape with a smooth minimum function.
- SDF Shape BlendCombine circles, boxes, and smooth min to build a smoothly blended compound shape.