GLSL Learning

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:

aresult
0.0100% x
0.2575% x, 25% y
0.5half and half
1.0100% 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), where mask is 0 outside and 1 inside the shape.
  • Animating between states: mix(start, end, progress) with progress driven 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), not mix(t, colorA, colorB).
  • Letting a go outside 0..1. mix does not clamp, so a = 1.5 overshoots past y. Wrap it in clamp if the input can exceed the range.
  • Mixing a vec3 with a vec4. Both x and y must have the same type.

Related functions

Tutorials that use mix()