Convert between OKLCH polar and OKLAB rectangular coordinates with real-time preview
#ff0044
#ff0044
// 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
};
}
// 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)
// Ensure hue is positive
if (oklchH < 0) oklchH += 360;
return {
l: Math.round(oklchL * 1000) / 1000,
c: Math.round(oklchC * 1000) / 1000,
h: Math.round(oklchH * 10) / 10
};
}
// Example usage
const oklchColor = { l: 0.628, c: 0.258, h: 29.23 };
const oklabColor = oklchToOklab(oklchColor);
console.log(oklabColor); // { l: 0.628, a: 0.226, b: 0.125 }
// Color mixing example using OKLAB
function mixOklabColors(color1, color2, ratio = 0.5) {
return {
l: color1.l * (1 - ratio) + color2.l * ratio,
a: color1.a * (1 - ratio) + color2.a * ratio,
b: color1.b * (1 - ratio) + color2.b * ratio
};
}