color.ts (989B)
1 import type { Color } from '$lib/types'; 2 3 // from https://observablehq.com/@shan/oklab-color-wheel 4 5 const gamma = (x: number) => (x >= 0.0031308 ? 1.055 * Math.pow(x, 1 / 2.4) - 0.055 : 12.92 * x) 6 7 export const oklab = (L: number, a: number, b: number): Color => { 8 const l_ = L + 0.3963377774 * a + 0.2158037573 * b; 9 const m_ = L - 0.1055613458 * a - 0.0638541728 * b; 10 const s_ = L - 0.0894841775 * a - 1.2914855480 * b; 11 const l = l_ * l_ * l_; 12 const m = m_ * m_ * m_; 13 const s = s_ * s_ * s_; 14 15 return { 16 r: 255 * gamma(+4.0767245293 * l - 3.3072168827 * m + 0.2307590544 * s), 17 g: 255 * gamma(-1.2681437731 * l + 2.6093323231 * m - 0.3411344290 * s), 18 b: 255 * gamma(-0.0041119885 * l - 0.7034763098 * m + 1.7068625689 * s) 19 }; 20 } 21 22 export const oklch = (lightness: number, chroma: number, hue: number): Color => { 23 const h = 2 * Math.PI * (hue / 360); 24 const C = chroma; 25 const a = C * Math.cos(h); 26 const b = C * Math.sin(h); 27 28 return oklab(lightness, a, b) 29 }