Convert between OKLAB rectangular and OKLCH polar coordinates with real-time preview
#ff0044
#ff0044
// OKLAB to OKLCH conversion function
function oklabToOklch(oklab) {
const { l, a, b } = oklab;
// Convert rectangular to polar coordinates
const oklchL = l; // Lightness remains the same
const oklchC = Math.sqrt(a * a + b * b); // Chroma (distance from center)
let oklchH = Math.atan2(b, a) * 180 / Math.PI; // Hue (angle in degrees)
// Ensure hue is positive (0-360°)
if (oklchH < 0) oklchH += 360;
return {
l: Math.round(oklchL * 1000) / 1000,
c: Math.round(oklchC * 1000) / 1000,
h: Math.round(oklchH * 10) / 10
};
}
// OKLCH to OKLAB conversion function
function oklchToOklab(oklch) {
const { l, c, h } = oklch;
// Convert hue from degrees to radians
const hueRadians = h * Math.PI / 180;
// Convert polar to rectangular coordinates
const oklabL = l; // Lightness remains the same
const oklabA = c * Math.cos(hueRadians); // A component (green-red axis)
const oklabB = c * Math.sin(hueRadians); // B component (blue-yellow axis)
return {
l: Math.round(oklabL * 1000) / 1000,
a: Math.round(oklabA * 1000) / 1000,
b: Math.round(oklabB * 1000) / 1000
};
}
// Example usage
const oklabColor = { l: 0.628, a: 0.226, b: 0.125 };
const oklchColor = oklabToOklch(oklabColor);
console.log(oklchColor); // { l: 0.628, c: 0.258, h: 29.23 }
// Color picker integration example
function createColorPicker(oklabColor) {
const oklch = oklabToOklch(oklabColor);
// Use OKLCH for intuitive UI controls
const hueSlider = oklch.h; // 0-360° for hue wheel
const chromaSlider = oklch.c; // 0-0.4 for saturation
const lightnessSlider = oklch.l; // 0-1 for brightness
return { hueSlider, chromaSlider, lightnessSlider };
}