Saturon LogoSaturon

saturon/contrast

Calculate the WCAG 2.1 relative luminance contrast ratio between two colors.

The saturon/contrast subpath exposes the standalone contrast() function, which computes the WCAG 2.1 relative luminance contrast ratio between any two colors.

contrast()

Calculates the contrast ratio between two ColorData objects by converting both into the XYZ-D65 color space to extract their relative luminance (YY component) and applying the WCAG 2.1 contrast formula.

import { contrast } from "saturon/contrast";

const white = { model: "rgb", coords: [255, 255, 255] };
const black = { model: "rgb", coords: [0, 0, 0] };

const ratio = contrast(white, black);
console.log(ratio); // 21

Signature

function contrast(color1: ColorData, color2: ColorData): number;

Parameters

ParameterTypeDescription
color1ColorDataThe first raw ColorData object to evaluate.
color2ColorDataThe second raw ColorData object to evaluate against.

Returns

A number ranging from 1 (identical relative luminance) to 21 (maximum contrast, e.g., pure black vs. pure white).

Behavior

  1. Converts both color1 and color2 to the xyz-d65 color space using convert().
  2. Extracts the relative luminance coordinate (YY, the second component in the XYZ array) for each color via toArray().
  3. Determines L1L_1 (maximum luminance) and L2L_2 (minimum luminance) and evaluates the standard ratio formula:

Contrast=L1+0.05L2+0.05\text{Contrast} = \frac{L_1 + 0.05}{L_2 + 0.05}

Usage Example

import { contrast } from "saturon/contrast";

const text = { model: "rgb", coords: [50, 50, 50, 1] };
const background = { model: "rgb", coords: [240, 240, 240, 1] };

const ratio = contrast(text, background);

// Check WCAG AA compliance for normal text (minimum 4.5:1)
const isAACompliant = ratio >= 4.5;
console.log(`Contrast Ratio: ${ratio.toFixed(2)}:1`);
console.log(`Passes WCAG AA: ${isAACompliant}`);

On this page