contrastRatio
Returns the WCAG 2.1 contrast ratio between two colors, from 1 (identical luminance) to 21 (black on white).
import { contrastRatio } from '@pbroom/color-kit';metrics.ts:174function contrastRatio(
color1: Color,
color2: Color,
options?: ContrastOptions,
): number;Symmetric in its arguments. Colors are measured as in relativeLuminance; the result is unrounded, so black on white is 20.999999999999986 rather than exactly 21.
Parameters
- options?
ContrastOptions - Display gamut and channel precision.
Returns
numberContrast ratio in [1, 21].
Throws
- When
options.gamutis not'srgb'or'display-p3'.
Example
import { contrastRatio, parse } from '@pbroom/color-kit';
contrastRatio(parse('#777'), parse('#fff')); // → ≈ 4.478
contrastRatio(parse('#000'), parse('#fff')).toFixed(2); // → '21.00'