| 1 |
import ColorSpace from "../ColorSpace.js"; |
| 2 |
import sRGB from "./srgb.js"; |
| 3 |
|
| 4 |
export default new ColorSpace({ |
| 5 |
id: "hsl", |
| 6 |
name: "HSL", |
| 7 |
coords: { |
| 8 |
h: { |
| 9 |
refRange: [0, 360], |
| 10 |
type: "angle", |
| 11 |
name: "Hue", |
| 12 |
}, |
| 13 |
s: { |
| 14 |
range: [0, 100], |
| 15 |
name: "Saturation", |
| 16 |
}, |
| 17 |
l: { |
| 18 |
range: [0, 100], |
| 19 |
name: "Lightness", |
| 20 |
}, |
| 21 |
}, |
| 22 |
|
| 23 |
base: sRGB, |
| 24 |
rgbGamut: sRGB, |
| 25 |
|
| 26 |
// Adapted from https://drafts.csswg.org/css-color-4/better-rgbToHsl.js |
| 27 |
fromBase: rgb => { |
| 28 |
let max = Math.max(...rgb); |
| 29 |
let min = Math.min(...rgb); |
| 30 |
let [r, g, b] = rgb; |
| 31 |
let [h, s, l] = [null, 0, (min + max) / 2]; |
| 32 |
let d = max - min; |
| 33 |
|
| 34 |
if (d !== 0) { |
| 35 |
s = l === 0 || l === 1 ? 0 : (max - l) / Math.min(l, 1 - l); |
| 36 |
|
| 37 |
switch (max) { |
| 38 |
case r: |
| 39 |
h = (g - b) / d + (g < b ? 6 : 0); |
| 40 |
break; |
| 41 |
case g: |
| 42 |
h = (b - r) / d + 2; |
| 43 |
break; |
| 44 |
case b: |
| 45 |
h = (r - g) / d + 4; |
| 46 |
} |
| 47 |
|
| 48 |
h = h * 60; |
| 49 |
} |
| 50 |
|
| 51 |
// Very out of gamut colors can produce negative saturation |
| 52 |
// If so, just rotate the hue by 180 and use a positive saturation |
| 53 |
// see https://github.com/w3c/csswg-drafts/issues/9222 |
| 54 |
if (s < 0) { |
| 55 |
h += 180; |
| 56 |
s = Math.abs(s); |
| 57 |
} |
| 58 |
|
| 59 |
if (h >= 360) { |
| 60 |
h -= 360; |
| 61 |
} |
| 62 |
|
| 63 |
return [h, s * 100, l * 100]; |
| 64 |
}, |
| 65 |
|
| 66 |
// Adapted from https://en.wikipedia.org/wiki/HSL_and_HSV#HSL_to_RGB_alternative |
| 67 |
toBase: hsl => { |
| 68 |
let [h, s, l] = hsl; |
| 69 |
h = h % 360; |
| 70 |
|
| 71 |
if (h < 0) { |
| 72 |
h += 360; |
| 73 |
} |
| 74 |
|
| 75 |
s /= 100; |
| 76 |
l /= 100; |
| 77 |
|
| 78 |
function f (n) { |
| 79 |
let k = (n + h / 30) % 12; |
| 80 |
let a = s * Math.min(l, 1 - l); |
| 81 |
return l - a * Math.max(-1, Math.min(k - 3, 9 - k, 1)); |
| 82 |
} |
| 83 |
|
| 84 |
return [f(0), f(8), f(4)]; |
| 85 |
}, |
| 86 |
|
| 87 |
formats: { |
| 88 |
hsl: { |
| 89 |
coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"], |
| 90 |
}, |
| 91 |
hsla: { |
| 92 |
coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"], |
| 93 |
commas: true, |
| 94 |
alpha: true, |
| 95 |
}, |
| 96 |
} |
| 97 |
}); |