Created
June 14, 2020 23:23
-
-
Save Ademking/560d541e87043bfff0eb8470d3ef4894 to your computer and use it in GitHub Desktop.
JS: Find Nearest Color from Array
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
const baseColors = [ | |
{ | |
"hex": "#FFFFFF", | |
"name": "White", | |
}, | |
{ | |
"hex": "#000000", | |
"name": "Black", | |
}, | |
{ | |
"hex": "#808080", | |
"name": "Grey", | |
}, | |
{ | |
"hex": "#ff0000", | |
"name": "Red", | |
}, | |
{ | |
"hex": "#ffa500", | |
"name": "Orange", | |
}, | |
{ | |
"hex": "#ffff00", | |
"name": "Yellow", | |
}, | |
{ | |
"hex": "#008000", | |
"name": "Green", | |
}, | |
{ | |
"hex": "#0000ff", | |
"name": "Blue", | |
}, | |
{ | |
"hex": "#4b0082", | |
"name": "Indigo", | |
}, | |
{ | |
"hex": "#ee82ee", | |
"name": "Violet", | |
}, | |
] | |
// from https://stackoverflow.com/a/5624139 | |
function hexToRgb(hex) { | |
var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i; | |
hex = hex.replace(shorthandRegex, function(m, r, g, b) { | |
return r + r + g + g + b + b; | |
}); | |
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; | |
} | |
// Distance between 2 colors (in RGB) | |
// https://stackoverflow.com/questions/23990802/find-nearest-color-from-a-colors-list | |
function distance(a, b) { | |
return Math.sqrt(Math.pow(a.r - b.r, 2) + Math.pow(a.g - b.g, 2) + Math.pow(a.b - b.b, 2)); | |
} | |
// return nearest color from array | |
function nearestColor(colorHex){ | |
var lowest = Number.POSITIVE_INFINITY; | |
var tmp; | |
let index = 0; | |
baseColors.forEach( (el, i) => { | |
tmp = distance(hexToRgb(colorHex), hexToRgb(el.hex)) | |
if (tmp < lowest) { | |
lowest = tmp; | |
index = i; | |
}; | |
}) | |
return baseColors[index]; | |
} | |
console.log(nearestColor("#FFFFFF")); | |
174n
commented
Apr 26, 2021
Thanks!
Just wonderful, thank you so much.
https://codepen.io/templatetuners/pen/RwOeLxz
something is wrong here? getting strange results
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment