Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
105
rated 0 times [  110] [ 5]  / answers: 1 / hits: 73867  / 12 Years ago, mon, august 20, 2012, 12:00:00

I'm trying to evaluate the darkness of a color chosen by a color picker to see if it's "too black", and if so, set it to white. I thought I could use the first characters of the hex value to pull this off. It's working, but it's switching some legitimately "light" colors too.


I have the following code:


if (lightcolor.substring(0, 3) == "#00" || lightcolor.substring(0, 3) == "#010") {
lightcolor = "#FFFFFF";
color = lightcolor;
}

There must be a more efficient way with hex math to know that a color has gone beyond a certain level of darkness? Like if lightcolor + "some hex value" <= "some hex value" then set it to white.


I have tinyColor added, which might be of use for this, but I don't know for sure.


More From » colors

 Answers
13

You have to extract the three RGB components individually, and then use a standard formula to convert the resulting RGB values into their perceived brightness.



Assuming a six character colour:



var c = c.substring(1);      // strip #
var rgb = parseInt(c, 16); // convert rrggbb to decimal
var r = (rgb >> 16) & 0xff; // extract red
var g = (rgb >> 8) & 0xff; // extract green
var b = (rgb >> 0) & 0xff; // extract blue

var luma = 0.2126 * r + 0.7152 * g + 0.0722 * b; // per ITU-R BT.709

if (luma < 40) {
// pick a different colour
}


EDIT



Since May 2014 tinycolor now has a getBrightness() function, albeit using the CCIR601 weighting factors instead of the ITU-R ones above.



EDIT



The resulting luma value range is 0..255, where 0 is the darkest and 255 is the lightest. Values greater than 128 are considered light by tinycolor. (shamelessly copied from the comments by @pau.moreno and @Alnitak)


[#83529] Saturday, August 18, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nestorjarettg

Total Points: 451
Total Questions: 108
Total Answers: 108

Location: Rwanda
Member since Thu, Feb 10, 2022
2 Years ago
;