Skip to content

Instantly share code, notes, and snippets.

@Ademking
Created June 14, 2020 23:23
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Ademking/560d541e87043bfff0eb8470d3ef4894 to your computer and use it in GitHub Desktop.
Save Ademking/560d541e87043bfff0eb8470d3ef4894 to your computer and use it in GitHub Desktop.
JS: Find Nearest Color from Array
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
Copy link

174n commented Apr 26, 2021

const colors = ["#FFFFFF", "#000000", "#808080", "#ff0000", "#ffa500", "#ffff00", "#008000", "#0000ff", "#4b0082", "#ee82ee"];
const hexToRgb = hex => hex.slice(1).replace(/^(.)(.)(.)$/gi, "$1$1$2$2$3$3").match(/.{2}/g).map(c => parseInt(c, 16));
const distance = (a, b) => Math.sqrt(Math.pow(a[0] - b[0], 2) + Math.pow(a[1] - b[1], 2) + Math.pow(a[2] - b[2], 2));
const nearestColor = colorHex =>
  colors.reduce((a,v,i,arr) =>
    a = distance(hexToRgb(colorHex), hexToRgb(v)) < a[0] ? [distance(hexToRgb(colorHex), hexToRgb(v)), v] : a, [Number.POSITIVE_INFINITY, colors[0]])[1];

@nsaicharan
Copy link

Thanks!

@bugsysailor
Copy link

Just wonderful, thank you so much.

@templatetuners
Copy link

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