color-thief icon indicating copy to clipboard operation
color-thief copied to clipboard

Lightest color from the color palette

Open tiagogon opened this issue 10 years ago • 2 comments

Since i would like to use this scrip to get a color for a background (that i want to be light), I would like to know if there is a way to get from the color palette the lightest color?

Thank you!

tiagogon avatar Oct 28 '14 21:10 tiagogon

Maybe this is something for you: https://gist.github.com/Pluto1010/f26beed7fdebfb2e2110

Pluto1010 avatar Feb 21 '16 07:02 Pluto1010

I know this is an old thread but just in case someone comes across this here's a solution.

The calculation used is Relative Luminance. There are other options though. You should also note that the function will only return one color, even if there are several in the palette which have the same luminance value.

var lightestColor = palette.reduce(function(previousValue, currentValue){
    var currLightNess = (0.2126*currentValue[0] + 0.7152*currentValue[1] + 0.0722*currentValue[2]);
    var prevLightNess = (0.2126*previousValue[0] + 0.7152*previousValue[1] + 0.0722*previousValue[2]);
    return (prevLightNess < currLightNess) ? currentValue : previousValue;
});

Assuming the below input:

var palette = [[58,40,29],[179,132,42],[110,204,222],[213,219,185],[162,184,117],[129,119,105],[43,125,148],[172,198,208],[44,68,132]];

you'll get a return value of:

lightestColor = [213, 219, 185]

AlfredJKwack avatar Apr 01 '16 10:04 AlfredJKwack