Menu

Perceptual Color Systems in JavaScript: OKLCH Conversion and WCAG 2.1 Contrast Auto-Fix
📰

Perceptual Color Systems in JavaScript: OKLCH Conversion and WCAG 2.1 Contrast Auto-Fix

DEV Community: css·Bastien Sulyan·3 days ago
#5jval6gf
#devtocss#devto#dev#math#perceptual
Reading 0:00
15s threshold

Design systems built on cylindrical hsl(h, s, l) math consistently run into the same perceptual flaw: human vision does not perceive equal lightness across hues. In HSL, pure yellow ( hsl(60, 100%, 50%) , #FFFF00 ) and pure blue ( hsl(240, 100%, 50%) , #0000FF ) both report a lightness of 50% . Yet their WCAG 2.1 relative luminances are 0.9278 and 0.0722 respectively—meaning white text is illegible on yellow ( 1.07:1 ) while passing AAA on blue ( 8.59:1 ).

Below is the mathematical implementation for converting sRGB colors into Björn Ottosson's perceptual OKLCH color space, evaluating WCAG 2.1 luminance contrast, and automatically solving for the nearest accessible foreground lightness—all in zero-dependency JavaScript.

(If you want to drop these functions directly into a Node.js or browser project, the open-source package sunasty-color-math and the online Sunasty Color Picker implement the full pipeline client-side.)

1.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.