Skip to content

Instantly share code, notes, and snippets.

@connebs
Last active November 22, 2019 11:21
Show Gist options
  • Select an option

  • Save connebs/25b362d8d29330152518080188d61c00 to your computer and use it in GitHub Desktop.

Select an option

Save connebs/25b362d8d29330152518080188d61c00 to your computer and use it in GitHub Desktop.
Takes a hex color value and spits out a color based on some simple parameters
const greyThresh = 0.2;
const bwDelta = 20;
const hueMap = {
0: "red",
60: "yellow",
120: "green",
180: "teal",
240: "blue",
300: "purple",
360: "red"
};
function getClosestColorName(hex) {
const [r, g, b] = hex
.slice(1)
.split(/(.{2})/)
.filter(_ => _)
.map(x => parseInt(x, 16));
let v = Math.max(r, g, b),
n = v - Math.min(r, g, b);
let h =
n && (v == r ? (g - b) / n : v == g ? 2 + (b - r) / n : 4 + (r - g) / n);
[h, s, v] = [60 * (h < 0 ? h + 6 : h), v && n / v, v];
return v < 0 + bwDelta
? "black"
: s < greyThresh
? v > 255 - bwDelta
? "white"
: "grey"
: hueMap[
Object.keys(hueMap).reduce(
(p, n) => (Math.abs(p) > Math.abs(n - h) ? n - h : p),
Infinity
) + h
];
}
console.log(getClosestColorName("#a3fdb2"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment