GLSL built-in function
mix()
Linearly interpolates between x and y: returns x when a is 0.0, y when a is 1.0, and a blend in between.
Syntax
float mix(float x, float y, float a)
vec2 mix(vec2 x, vec2 y, float a)
vec3 mix(vec3 x, vec3 y, float a)
vec3 mix(vec3 x, vec3 y, vec3 a)
vec4 mix(vec4 x, vec4 y, float a)Parameters
- x
- The start value, returned when a is 0.0.
- y
- The end value, returned when a is 1.0.
- a
- The blend amount, usually between 0.0 and 1.0. Can be a vector to blend each component separately.
Return value
x * (1.0 - a) + y * a, with the same type as x.
Live example
Edit the code and the preview updates as you type.
How it works
mix(x, y, a) slides from x to y as a goes from 0 to 1. Think of a as a percentage:
| a | result |
|---|---|
| 0.0 | 100% x |
| 0.25 | 75% x, 25% y |
| 0.5 | half and half |
| 1.0 | 100% y |
The formula is x * (1.0 - a) + y * a. In the top half of the example a is uv.x, so the color moves evenly from red to blue. In the bottom half a comes from smoothstep, so the blend happens in a narrow, moving band.
Typical uses
- Gradients:
mix(colorA, colorB, uv.y)for a vertical sky gradient. - Drawing a shape over a background:
mix(background, shapeColor, mask), wheremaskis 0 outside and 1 inside the shape. - Animating between states:
mix(start, end, progress)withprogressdriven by time. - Blending per channel:
mix(a, b, vec3(0.0, 0.5, 1.0))uses a different amount for red, green and blue.
Common mistakes
- Swapping the arguments. The blend amount is the third argument:
mix(colorA, colorB, t), notmix(t, colorA, colorB). - Letting
ago outside 0..1.mixdoes not clamp, soa = 1.5overshoots past y. Wrap it inclampif the input can exceed the range. - Mixing a
vec3with avec4. Both x and y must have the same type.
Related functions
Tutorials that use mix()
- Clamp DemoUse clamp() to keep values in range.
- Contrast with pow()Apply pow() to reshape a gradient curve.
- Grid LinesUse fract() and step() to draw grid lines.
- Horizontal GradientCreate a simple left-to-right gradient using vUv.x and mix().
- Smooth BandCreate a soft horizontal band using smoothstep().
- Vertical GradientCreate a bottom-to-top gradient with vUv.y.