Last active
June 13, 2020 07:42
-
-
Save vansosnin/098ad1efdbf6c6971bbd13be98cc605f to your computer and use it in GitHub Desktop.
Find closest colors
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://gamma-cveta.ru/kolerovka-krasok | |
// https://www.robotint.ru | |
// run example | |
getSimilarColors("#41594F", 60, 60, 50); | |
// utility | |
const clamp = (value, min, max) => { | |
let _value = value; | |
_value = Math.max(min, _value); | |
_value = Math.min(max, _value); | |
return _value; | |
}; | |
const clampByte = value => clamp(value, 0, 255); | |
const hexToRgb = hex => { | |
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); | |
if (result) { | |
const [rgb, r, g, b] = result.map(ch => parseInt(ch, 16)); | |
return [r, g, b]; | |
} | |
return [0, 0, 0]; | |
}; | |
function getSimilarColors( | |
hexColor, | |
rPercent = 50, | |
gPercent = 50, | |
bPercent = 50 | |
) { | |
const rgbColor = hexToRgb(hexColor); | |
return [ | |
...document | |
.querySelector(".tint-cp-scrollable") | |
.querySelectorAll("tint-div[data-collection-name]") | |
] | |
.map(node => { | |
node.style.display = "none"; | |
return node; | |
}) | |
.filter(node => { | |
const rgbDiffs = hexToRgb(node.getAttribute("data-hex")).map( | |
(channel, index) => { | |
const percent = index === 0 ? rPercent : index === 1 ? gPercent : bPercent; | |
const min = Math.round(channel - (channel / 100) * percent); | |
const max = Math.round(channel + (channel / 100) * percent); | |
return [clampByte(min), clampByte(max)]; | |
} | |
); | |
return rgbDiffs.every((diff, index) => diff[0] <= rgbColor[index] && rgbColor[index] <= diff[1]); | |
}) | |
.map(node => { | |
node.style.display = "block"; | |
return node.getAttribute("data-name"); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment