|
1 | | -// // Convert hex to RGB first |
2 | | -// export default function hexToHsl(hex: string) { |
3 | | -// // Convert hex to RGB first |
4 | | -// let r, g, b; |
5 | | -// if (hex.length === 4) { |
6 | | -// r = "0x" + hex[1] + hex[1]; |
7 | | -// g = "0x" + hex[2] + hex[2]; |
8 | | -// b = "0x" + hex[3] + hex[3]; |
9 | | -// } else if (hex.length === 7) { |
10 | | -// r = "0x" + hex[1] + hex[2]; |
11 | | -// g = "0x" + hex[3] + hex[4]; |
12 | | -// b = "0x" + hex[5] + hex[6]; |
13 | | -// } |
14 | | -// // Then to HSL |
15 | | -// r /= 255; |
16 | | -// g /= 255; |
17 | | -// b /= 255; |
18 | | -// let cmin = Math.min(r, g, b), |
19 | | -// cmax = Math.max(r, g, b), |
20 | | -// delta = cmax - cmin, |
21 | | -// h = 0, |
22 | | -// s = 0, |
23 | | -// l = 0; |
24 | | - |
25 | | -// if (delta === 0) h = 0; |
26 | | -// else if (cmax === r) h = ((g - b) / delta) % 6; |
27 | | -// else if (cmax === g) h = (b - r) / delta + 2; |
28 | | -// else h = (r - g) / delta + 4; |
29 | | - |
30 | | -// h = Math.round(h * 60); |
31 | | - |
32 | | -// if (h < 0) h += 360; |
33 | | - |
34 | | -// l = (cmax + cmin) / 2; |
35 | | -// s = delta === 0 ? 0 : delta / (1 - Math.abs(2 * l - 1)); |
36 | | -// s = +(s * 100).toFixed(1); |
37 | | -// l = +(l * 100).toFixed(1); |
38 | | - |
39 | | -// console.log( |
40 | | -// "hsl(" + Math.round(h) + "," + Math.round(s) + "," + Math.round(l) + ")" |
41 | | -// ); |
42 | | -// } |
| 1 | +export default function hexToHsl(hex: string): number[] { |
| 2 | + let rgb = hex |
| 3 | + .replace( |
| 4 | + /^#?([a-f\d])([a-f\d])([a-f\d])$/i, |
| 5 | + (m, r, g, b) => "#" + r + r + g + g + b + b |
| 6 | + ) |
| 7 | + .substring(1) |
| 8 | + .match(/.{2}/g) |
| 9 | + .map((x) => parseInt(x, 16)); |
| 10 | + (rgb[0] /= 255), (rgb[1] /= 255), (rgb[2] /= 255); |
| 11 | + var max = Math.max(rgb[0], rgb[1], rgb[2]), |
| 12 | + min = Math.min(rgb[0], rgb[1], rgb[2]); |
| 13 | + var h: number, |
| 14 | + s: number, |
| 15 | + l: number = (max + min) / 2; |
| 16 | + if (max == min) { |
| 17 | + h = s = 0; |
| 18 | + } else { |
| 19 | + var d = max - min; |
| 20 | + s = l > 0.5 ? d / (2 - max - min) : d / (max + min); |
| 21 | + switch (max) { |
| 22 | + case rgb[0]: |
| 23 | + h = (rgb[1] - rgb[2]) / d + (rgb[1] < rgb[2] ? 6 : 0); |
| 24 | + break; |
| 25 | + case rgb[1]: |
| 26 | + h = (rgb[2] - rgb[1]) / d + 2; |
| 27 | + break; |
| 28 | + case rgb[2]: |
| 29 | + h = (rgb[0] - rgb[1]) / d + 4; |
| 30 | + break; |
| 31 | + } |
| 32 | + h /= 6; |
| 33 | + } |
| 34 | + return [h, s, l]; |
| 35 | +} |
0 commit comments