GLSL built-in function
length()
Returns the length of a vector, its distance from the origin. length(p) is the starting point for drawing circles.
Syntax
float length(float x)
float length(vec2 x)
float length(vec3 x)
float length(vec4 x)Parameters
- x
- The vector to measure.
Return value
A single float greater than or equal to 0, even when x is a vector.
Live example
Edit the code and the preview updates as you type.
How it works
length(v) measures how long a vector is, using Pythagoras: length(vec2(3.0, 4.0)) is 5.0, the same as sqrt(3.0 * 3.0 + 4.0 * 4.0).
With centered coordinates p, length(p) is the distance from the pixel to the center of the canvas. All pixels with the same distance form a circle, so:
float d = length(p);
float circle = step(d, 0.5); // 1.0 inside a circle of radius 0.5
The example also feeds the distance to fract, which repeats it into rings that drift outward.
Typical uses
- Circles and rings: compare
length(p - center)with a radius. - Radial gradients and vignettes:
1.0 - length(p)is bright in the middle and dark at the edges. - Circle SDF:
length(p) - radiusis negative inside, zero on the edge and positive outside.
Common mistakes
- Forgetting to center coordinates.
length(uv)measures from the bottom-left corner, so circles appear cut off in the corner. - Stretched circles on non-square canvases. Correct the aspect ratio first:
p.x *= u_resolution.x / u_resolution.y. - Using
lengthjust to compare distances in a loop.dot(v, v)gives the squared length without the square root.
Related functions
distance()
Returns the distance between two points, the same as length(p0 - p1).
dot()
Returns the dot product of two vectors. For unit vectors it measures how much they point the same way: 1.0 same direction, 0.0 perpendicular, -1.0 opposite.
normalize()
Returns a vector pointing in the same direction as x but with length 1.0. Keeps the direction, drops the size.
Tutorials that use length()
- Drawing CirclesLearn to draw basic shapes using distance functions and understand the pixel coordinate system and distance function applications.
- Circle OutlineDraw a ring by using abs(distance - radius) and smoothstep().
- Vignette (Edge Darkening)Use distance to center and smoothstep() to darken edges.
- Circle Drawing (Distance Function)Draw a circle using normalized coordinates and the distance function length(), then color it with a simple conditional.
- Aspect-Ratio Corrected UVLearn to correct UV aspect ratio with u_resolution so circles stay round on non-square canvases.
- SDF RingDraw a ring using a distance field: abs(length(p) - r) and smoothstep for smooth edges.