OKLCH Color Converter — TypeScript source
Convert between hex and OKLCH — the perceptual color space behind modern CSS. Live lightness, chroma, and hue sliders with the sRGB gamut edge shown on the chroma rail; out-of-gamut points gamut-map exactly like browsers do.
This is the TypeScript implementation — the same logic the interactive tool runs, in a shareable, citable form.
// Pure surface of the oklch-converter tool (slug: oklch-converter). OKLab /
// OKLCH per Björn Ottosson's published matrices — hand-rolled so the contract
// is explicit for the Go twin (same constants, same epsilon clamps). Hex
// endpoints reuse colorConvert's rgb<->hex. Out-of-gamut results clamp per
// channel and flag inGamut=false; maxChroma finds the sRGB gamut edge by
// bisection for the island's chroma slider rail.
import { hexToRgb, rgbToHex } from './colorConvert';
export interface Oklch {
/** Lightness 0..1 */
L: number;
/** Chroma, typically 0..0.4 */
C: number;
/** Hue in degrees, 0..360 (0 when C ≈ 0) */
H: number;
}
export interface SrgbResult {
hex: string;
rgb: [number, number, number];
/** False when the exact OKLCH point falls outside sRGB and was clamped. */
inGamut: boolean;
}
const clamp01 = (x: number): number => Math.min(1, Math.max(0, x));
const toLinear = (c: number): number => (c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4));
const toGamma = (c: number): number => (c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055);
const round255 = (x: number): number => Math.round(clamp01(x) * 255);
/** sRGB (0..255) → OKLCH. Uses Ottosson's forward matrices. */
export function srgbToOklch(r: number, g: number, b: number): Oklch {
const lr = toLinear(r / 255);
const lg = toLinear(g / 255);
const lb = toLinear(b / 255);
const l = Math.cbrt(0.4122214708 * lr + 0.5363325363 * lg + 0.0514459929 * lb);
const m = Math.cbrt(0.2119034982 * lr + 0.6806995451 * lg + 0.1073969566 * lb);
const s = Math.cbrt(0.0883024619 * lr + 0.2817188376 * lg + 0.6299787005 * lb);
const L = 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s;
const a = 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s;
const bb = 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s;
const C = Math.hypot(a, bb);
let H = C < 1e-6 ? 0 : (Math.atan2(bb, a) * 180) / Math.PI;
if (H < 0) H += 360;
return { L, C, H };
}
/** Linear sRGB channels for an OKLCH point (unclamped). */
function linearFromOklch(L: number, C: number, H: number): [number, number, number] {
const rad = (H * Math.PI) / 180;
const a = C * Math.cos(rad);
const b = C * Math.sin(rad);
const l = Math.pow(L + 0.3963377774 * a + 0.2158037573 * b, 3);
const m = Math.pow(L - 0.1055613458 * a - 0.0638541728 * b, 3);
const s = Math.pow(L - 0.0894841775 * a - 1.291485548 * b, 3);
return [
4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
-0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s,
];
}
/** OKLCH → sRGB hex. Out-of-gamut points are gamut-mapped by CHROMA
* REDUCTION (browser-style: show the brightest achievable color of that
* hue/lightness, not a per-channel clamp), and flagged inGamut=false. */
export function oklchToSrgb({ L, C, H }: Oklch): SrgbResult {
let [lr, lg, lb] = linearFromOklch(L, C, H);
const inGamut = lr >= -1e-4 && lr <= 1 + 1e-4 && lg >= -1e-4 && lg <= 1 + 1e-4 && lb >= -1e-4 && lb <= 1 + 1e-4;
if (!inGamut) {
// Shrink chroma to just inside the gamut edge (0.999 guard avoids the
// float boundary); hue and lightness stay — CSS gamut maps the same way.
const edge = maxChroma(L, H) * 0.999;
if (edge < C) [lr, lg, lb] = linearFromOklch(L, edge, H);
}
const rgb: [number, number, number] = [round255(toGamma(lr)), round255(toGamma(lg)), round255(toGamma(lb))];
return { hex: rgbToHex(rgb[0], rgb[1], rgb[2]), rgb, inGamut };
}
export function hexToOklch(hex: string): Oklch | null {
const rgb = hexToRgb(hex);
return rgb ? srgbToOklch(rgb[0], rgb[1], rgb[2]) : null;
}
export function oklchToHex(L: number, C: number, H: number): SrgbResult {
return oklchToSrgb({ L, C, H });
}
/** Largest chroma at this L/H that stays inside sRGB (bisection over [0, 0.5],
* ±0.001). Tests raw linear channels directly — never oklchToSrgb, which
* would recurse through its own gamut mapping. 0 when even C=0 is out
* (L outside 0..1). */
export function maxChroma(L: number, H: number): number {
const inGamutAt = (c: number): boolean => {
const [r, g, b] = linearFromOklch(L, c, H);
return r >= -1e-4 && r <= 1 + 1e-4 && g >= -1e-4 && g <= 1 + 1e-4 && b >= -1e-4 && b <= 1 + 1e-4;
};
if (!inGamutAt(0)) return 0;
let lo = 0;
let hi = 0.5; // above any sRGB-reachable chroma
for (let i = 0; i < 24; i++) {
const mid = (lo + hi) / 2;
if (inGamutAt(mid)) lo = mid;
else hi = mid;
}
return lo;
}
const OKLCH_RE =
/^oklch\(\s*([\d.]+)(%)?\s+([\d.]+)\s+(-?[\d.]+)(?:deg)?\s*(?:\/\s*([\d.]+)(%)?\s*)?\)$/i;
export interface ParsedOklch {
L: number;
C: number;
H: number;
alpha: number;
}
/** Parse CSS oklch() — accepts percent or 0..1 lightness, optional deg suffix,
* optional /alpha (percent or 0..1). Returns null on anything else. */
export function parseOklch(input: string): ParsedOklch | null {
const m = OKLCH_RE.exec(input.trim());
if (!m) return null;
const L = parseFloat(m[1]) / (m[2] ? 100 : 1);
const C = parseFloat(m[3]);
const H = parseFloat(m[4]);
const alpha = m[5] !== undefined ? parseFloat(m[5]) / (m[6] ? 100 : 1) : 1;
if (![L, C, H, alpha].every((v) => Number.isFinite(v))) return null;
return { L, C, H: ((H % 360) + 360) % 360, alpha };
}
/** Serialize to modern CSS: percent lightness, bare numbers, deg on hue. */
export function formatOklch({ L, C, H, alpha = 1 }: ParsedOklch): string {
const base = `oklch(${(L * 100).toFixed(1)}% ${C.toFixed(3)} ${H.toFixed(1)}deg)`;
return alpha < 1 ? base.replace(')', ` / ${alpha.toFixed(2)})`) : base;
}
Also available in 1 other language
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in several languages — the same contract, ported. Compare all languages side by side →