GLSL built-in function
fract()
Returns the fractional part of x, computed as x - floor(x), always in the range 0.0 to 1.0.
Syntax
float fract(float x)
vec2 fract(vec2 x)
vec3 fract(vec3 x)
vec4 fract(vec4 x)Parameters
- x
- The value to take the fractional part of. Vectors are processed per component.
Return value
A value of the same type as x, each component in [0.0, 1.0).
Live example
Edit the code and the preview updates as you type.
How it works
fract(x) keeps only what comes after the decimal point:
fract(2.75)is0.75fract(3.0)is0.0fract(-0.25)is0.75(because it isx - floor(x), andfloor(-0.25)is-1.0)
The trick is to scale first. uv goes from 0 to 1 once across the canvas. uv * 5.0 goes from 0 to 5, and fract of that restarts at 0 every time it crosses a whole number. The result is five copies of the 0..1 range, which the example shows as a 5 x 5 grid of gradients.
Typical uses
- Tiling:
fract(uv * n)gives every tile its own local 0..1 coordinates, so one shape repeats across the canvas. - Looping animation:
fract(u_time * 0.5)ramps from 0 to 1 every two seconds and jumps back. - Hash functions:
fract(sin(x) * 43758.5453)is the classic one-line pseudo-random number.
Common mistakes
- Forgetting that the jump from almost 1 back to 0 is a hard edge. If you need a smooth loop, use
sinorabs(fract(x) * 2.0 - 1.0)for a triangle wave. - Combining
fractandfloorwith different scale factors. The tile index isfloor(uv * n)and the local coordinate isfract(uv * n)with the same n.
Related functions
Tutorials that use fract()
- Grid LinesUse fract() and step() to draw grid lines.
- Stripes and BandsBuild repeating stripes with fract and step, and switch colors with mix.
- Hash Grid NoiseGenerate a random value per grid cell using a small hash function.
- Brick WallPractice building repeating patterns from UV coordinates.
- Moving GradientAnimate a gradient by shifting vUv.x over time.
- Scrolling StripesScroll stripes by adding time before fract().