GLSL Learning

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) - radius is 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 length just to compare distances in a loop. dot(v, v) gives the squared length without the square root.

Related functions

Tutorials that use length()