This repository has been archived by the owner on Oct 24, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
67 lines (60 loc) · 1.86 KB
/
script.js
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
function hexToRgb(hex) {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
result.shift();
return result.length === 3 ? result.map((x) => parseInt(x, 16)) : null;
}
colors.forEach((x, i) => {
colors[i].color = hexToRgb(x.color);
});
function getLuminosity(color) {
return (
[0.2126, 0.7152, 0.0722]
.map((x, i) => color[i] * x)
.reduce((x1, x2) => x1 + x2) / 255
);
}
function getClosestColor(color) {
return colors
.map((secondaryColor) => ({
difference: color
.map((x, i) => (x - secondaryColor.color[i]) ** 2)
.reduce((x1, x2) => x1 + x2),
data: secondaryColor,
}))
.sort((x1, x2) => x1.difference - x2.difference)[0].data;
}
function rgbToHex(color) {
return `#${color
.map((x) => x.toString(16))
.map((x) => `${x.length === 1 ? '0' : ''}${x}`)
.join('')}`;
}
function getInverseColor(color) {
return color.map((x) => 255 - x);
}
function updateData(color) {
const brightness = getLuminosity(color);
[header, hex, colorData].forEach((x) => {
x.style.color = brightness < 0.5 ? 'white' : 'black';
});
colorData.innerHTML = `${getClosestColor(color).name}<br>RGB: ${color.join(
', '
)}<br>Brightness: ${Math.round(brightness * 100)}%<br>Inverse: ${rgbToHex(
getInverseColor(color)
)}`;
document.body.style.backgroundColor = hex.innerHTML;
}
document.addEventListener('keydown', (event) => {
const key = event.key.toLowerCase();
if ('0123456789abcdef'.includes(key)) {
const MAX_LENGTH = 7;
if (hex.innerHTML.length < MAX_LENGTH) {
hex.innerHTML += key;
if (hex.innerHTML.length === MAX_LENGTH) {
updateData(hexToRgb(hex.innerHTML.substring(1, hex.innerHTML.length)));
}
}
} else if (key === 'backspace' && hex.innerHTML.length > 1) {
hex.innerHTML = hex.innerHTML.substring(0, hex.innerHTML.length - 1);
}
});