-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcolorUtils.js
More file actions
82 lines (72 loc) · 1.92 KB
/
colorUtils.js
File metadata and controls
82 lines (72 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// Color conversion utilities
export const hslToHex = (h, s, l) => {
l /= 100;
const a = (s * Math.min(l, 1 - l)) / 100;
const f = (n) => {
const k = (n + h / 30) % 12;
const color = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
return Math.round(255 * color)
.toString(16)
.padStart(2, '0');
};
return `#${f(0)}${f(8)}${f(4)}`;
};
export const hslToRgb = (h, s, l) => {
l /= 100;
const a = (s * Math.min(l, 1 - l)) / 100;
const f = (n) => {
const k = (n + h / 30) % 12;
const color = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
return Math.round(255 * color);
};
return { r: f(0), g: f(8), b: f(4) };
};
export const hexToHsl = (hex) => {
let r = 0,
g = 0,
b = 0;
if (hex.length === 4) {
r = '0x' + hex[1] + hex[1];
g = '0x' + hex[2] + hex[2];
b = '0x' + hex[3] + hex[3];
} else if (hex.length === 7) {
r = '0x' + hex[1] + hex[2];
g = '0x' + hex[3] + hex[4];
b = '0x' + hex[5] + hex[6];
}
r /= 255;
g /= 255;
b /= 255;
const cmin = Math.min(r, g, b),
cmax = Math.max(r, g, b),
delta = cmax - cmin;
let h = 0,
s = 0,
l = 0;
if (delta === 0) h = 0;
else if (cmax === r) h = ((g - b) / delta) % 6;
else if (cmax === g) h = (b - r) / delta + 2;
else h = (r - g) / delta + 4;
h = Math.round(h * 60);
if (h < 0) h += 360;
l = (cmax + cmin) / 2;
s = delta === 0 ? 0 : delta / (1 - Math.abs(2 * l - 1));
s = +(s * 100).toFixed(1);
l = +(l * 100).toFixed(1);
return { h, s, l };
};
export const getContrastColor = (hex) => {
const { r, g, b } = hexToRgb(hex);
const yiq = (r * 299 + g * 587 + b * 114) / 1000;
return yiq >= 128 ? '#000000' : '#ffffff';
};
const hexToRgb = (hex) => {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result
? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16),
}
: null;
};