Skip to content

Instantly share code, notes, and snippets.

@georules
Created March 16, 2016 20:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save georules/391062441353518c7030 to your computer and use it in GitHub Desktop.
Save georules/391062441353518c7030 to your computer and use it in GitHub Desktop.
var hextest = function(hex) {
function hexToRgb(hex) {
var 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;
}
function rgbToHsl(r, g, b){
r /= 255, g /= 255, b /= 255;
var max = Math.max(r, g, b), min = Math.min(r, g, b);
var h, s, l = (max + min) / 2;
if(max == min){
h = s = 0; // achromatic
}else{
var d = max - min;
s = (l > 0.5) ? d / (2 - max - min) : d / (max + min);
switch(max){
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
}
h /= 6;
}
return {h:h, s:s, l:l};
}
var returnColors = {
red : "#ea4235",
blue : "#4285f4",
yellow : "#fbbc05",
green : "#34a853"
}
colorshue = {}
Object.keys(returnColors).forEach(function(k){
c = returnColors[k]
rgb = hexToRgb(c)
hsl = rgbToHsl(rgb.r, rgb.g, rgb.b)
colorshue[k] = hsl.h
})
rgb = hexToRgb(hex)
hue = rgbToHsl(rgb.r, rgb.g, rgb.b).h
// hack for values of purple->red
if (hue > 0.77) {
return returnColors.red;
}
smallest_difference = 100000
smallest_key = ""
Object.keys(colorshue).forEach(function(k){
v = Math.abs(hue - colorshue[k])
if (v < smallest_difference) {
smallest_key = k
smallest_difference = v
}
})
return returnColors[smallest_key]
}
testcolor = "#ffe433"
returncolor = hextest(testcolor)
console.log("input", testcolor, "output", returncolor)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment