GLSL built-in function
abs()
Returns the absolute value of x: negative numbers become positive, positive numbers stay the same.
Syntax
float abs(float x)
vec2 abs(vec2 x)
vec3 abs(vec3 x)
vec4 abs(vec4 x)Parameters
- x
- The value to take the absolute value of. Vectors are processed per component.
Return value
A value of the same type as x, with every component greater than or equal to 0.
Live example
Edit the code and the preview updates as you type.
How it works
abs(x) throws away the minus sign. abs(-0.7) is 0.7, abs(0.7) is also 0.7.
On a centered coordinate system (p from -1 to 1), abs(p.x) is 0 in the middle and grows toward both edges. That turns a straight ramp into a V shape, which is why the example draws a V.
float y = abs(p.x); // left edge 1.0, center 0.0, right edge 1.0
Typical uses
- Mirror symmetry:
abs(p.x)folds the left half of the canvas onto the right half, so anything you draw appears twice. - Distance to a line:
abs(p.y - 0.3)is how far a pixel is from the horizontal liney = 0.3. - Box shapes:
max(abs(p.x), abs(p.y))gives square contours, the basis of rectangle SDFs.
Common mistakes
- Using
abson integer literals in GLSL ES 1.0: writeabs(-1.0), notabs(-1), because there is no integer overload. - Forgetting to center coordinates first. With
uvin 0..1 every value is already positive, soabs(uv.x)does nothing.
Related functions
Tutorials that use abs()
- Smooth BandCreate a soft horizontal band using smoothstep().
- Circle OutlineDraw a ring by using abs(distance - radius) and smoothstep().
- Rectangle BorderCreate a border by subtracting an inner rectangle mask from an outer one.
- SDF RingDraw a ring using a distance field: abs(length(p) - r) and smoothstep for smooth edges.
- Shape CompositionCombine circle and rectangle masks to build more complex shapes using min/max or simple compositing.
- Ping-Pong BandMove a soft band left and right using sin(u_time).