Colore JS

Search documentation

Find a function or jump to a section.
v2.0.1

contrastRatio

contrastRatio calculates the WCAG 2 contrast ratio for foreground and background colors. Colore composites translucent layers before measuring them so you can check the color that actually appears on the page.

Example

import { colore } from 'colore-js';
import { contrastRatio } from 'colore-js/fn';

colore('#767676').contrastRatio('#fff').toFixed(2); // '4.54'
contrastRatio('#777', '#fff').toFixed(2);           // '4.48'

Syntax

colore(foreground).contrastRatio(background: ColorInput | Color): number
contrastRatio(foreground: ColorInput, background: ColorInput): number

Parameters

NameTypeDescription
foregroundColorInputText, icon or other color drawn over the background.
backgroundColorInputThe color immediately behind it.

Returns

Both APIs return the numerical ratio. For in-gamut sRGB colors, it runs from 1 (equal luminance) to 21 (black and white). Compare the raw value with your threshold and round only for display.

Throws

A ColorError when a color cannot be parsed.

Check translucent text

import { contrastRatio } from 'colore-js/fn';

contrastRatio('rgb(0 0 0 / 0.5)', '#fff').toFixed(2); // '3.98'
contrastRatio('rgb(0 0 0 / 0.5)', '#fff') >= 4.5;    // false

Colore layers the background over white, then the foreground over that result. If the actual canvas has another color, resolve the layers over that canvas first. Pass the foreground first when either color has opacity. For wide-gamut input, map it to sRGB before checking a WCAG sRGB threshold.