Mix two colors
Color::mix() accepts color objects or parseable strings, a ratio, and an interpolation space:
use PhpColor\Color\Color;
$middle = Color::mix('#ff0000', '#0000ff', 0.5);
$nearBlue = Color::mix('#ff0000', '#0000ff', 0.8);
echo $middle->toCss();
echo $nearBlue->toCss();
use PhpColor\Color\Color;
$middle = Color::mix('#ff0000', '#0000ff', 0.5);
$nearBlue = Color::mix('#ff0000', '#0000ff', 0.8);
echo $middle->toCss();
echo $nearBlue->toCss();
The ratio is clamped to 0..1: zero selects the first endpoint and one selects the second. The default interpolation space is Oklab, so the returned object is an OklabColor.
The other supported interpolation choice is linear-light sRGB:
use PhpColor\Color\Color;
$oklab = Color::mix('#ff0000', '#0000ff', 0.5, 'oklab');
$srgb = Color::mix('#ff0000', '#0000ff', 0.5, 'srgb');
echo $oklab::getSpaceName();
echo $srgb::getSpaceName();
use PhpColor\Color\Color;
$oklab = Color::mix('#ff0000', '#0000ff', 0.5, 'oklab');
$srgb = Color::mix('#ff0000', '#0000ff', 0.5, 'srgb');
echo $oklab::getSpaceName();
echo $srgb::getSpaceName();
The space names are oklab and srgb. sRGB mixing linearizes the RGB channels before interpolation and converts them back afterward. Alpha is linearly interpolated in both modes.
No other string is currently supported, including oklch. An unsupported mixing space raises InvalidColorException. This is narrower than the set of spaces accepted by to().
Blend a source over a backdrop
Mixing interpolates between two colors. Blending applies a blend mode to the receiver as the source, then alpha-composites it over a backdrop:
use PhpColor\Color\Color;
$source = Color::parse('rgb(255 0 0 / 0.5)');
$result = $source->blend('#0000ff', 'screen');
echo $result->toCss();
use PhpColor\Color\Color;
$source = Color::parse('rgb(255 0 0 / 0.5)');
$result = $source->blend('#0000ff', 'screen');
echo $result->toCss();
Blending calculations use sRGB channels. The result is converted back to the source object's concrete type.
Supported modes are:
normalmultiplyscreenoverlaydarkenlightencolor-dodgecolor-burnhard-lightsoft-lightdifferenceexclusion
normal is the default. An unknown mode currently falls back to normal blending rather than throwing, so validate a mode received from configuration or user input.
Choose mix() for a point along a transition or scale. Choose blend() when source/backdrop order, a blend mode, or alpha compositing matters.
For plain source-over transparency without a blend mode, use compositing directly and verify the visible result against the backdrop. Continue with Interpolate a brand transition, Check contrast after compositing, or Mix colors, Blend colors, and Composite colors for visible comparisons.