I have a list of hex colors #000000 values. How can I get the lightest color from a list of hex colors using javascript?
Any help will be appreciated
I have a list of hex colors #000000 values. How can I get the lightest color from a list of hex colors using javascript?
Any help will be appreciated
According to this formula, you can calculate the luminance (brightness) of an RGB color like this:
L = 0.2126*R + 0.7152*G + 0.0722*B;
you can apply this on hex which won't be hard, then get the color with the maximum brightness:
function lum(hex) {
var r = parseInt(hex.substr(1, 2), 16),
g = parseInt(hex.substr(3, 2), 16),
b = parseInt(hex.substr(5, 2), 16);
return 0.2126*r + 0.7152*g + 0.0722*b;;
}
function lightest(colors) {
var maxIndex = 0,
maxLum = lum(colors[0]);
for(var i = 1; i < colors.length; i++) {
var iLum = lum(colors[i]);
if(maxLum < iLum) {
maxLum = iLum;
maxIndex = i;
}
}
return colors[maxIndex];
}
console.log(lightest(["#ff0000", "#ffcd00", "#000000"]));