3

I am trying to find the correct color. For example if I have a dark green color then I need a light green color or if I have a light green color then I need a dark green color. I have a code which tells me if the color is dark or light.

function calcBrightness(red,green,blue) {
    return Math.sqrt(
        red * red * .299 +
        green * green * .587 +
        blue * blue * .114);          
}

var brightness = calcBrightness(red, green, blue);
var foreColor = (brightness < 130) ? "light" : "green";

I am able to detect if the color is dark or light but how can I get the dark color if the result is light or light color if the foreColor value is green?

Sumner Evans
  • 8,551
  • 5
  • 29
  • 46
user3754676
  • 301
  • 4
  • 16

3 Answers3

3

Convert RGB color to HSL (Hue, Saturation, Lightness) makes the problem much easier.

You can easily adjust the lightness of your color by changing the L value in HSL.

The algorithm is available here

(from the question Javascript convert HSB/HSV color to RGB accurately)

Community
  • 1
  • 1
MK Yung
  • 4,066
  • 6
  • 27
  • 34
3

Technically speaking, it's actually better to do light/darkness in the HSL color space.

To save you some hassle, there's some great javascript libraries out there that have all kinds of color manipulation, such as TinyColor.

You don't really define what "light" and "dark" verisons of the colors are, but here's a quick example I threw together using TinyColor: http://jsfiddle.net/cm00kb04/1/

Effectively this is doing:

function findTextColor(backgroundColor) {
    var c = tinycolor(backgroundColor);
    return c.isDark() ? c.lighten(50) : c.darken(50);
}

You can do various levels of lightening/darkening, as well as find mostReadable() color among other manipulations.

What will result in the best outcome is going to depend on the context: eg, if this is handling any possible color, if there is a theme it must work with, etc.

gregmac
  • 23,373
  • 10
  • 86
  • 115
  • in order to tinycolor.js i just need to use tinycolor.js file right? because there are so many files on Github – user3754676 Feb 24 '15 at 03:37
  • 1
    @user3754676 yes, it is a standalone library. The other files in the project are for demos, unit tests, and building/packaging the library itself (eg: for [npm](https://www.npmjs.com/package/tinycolor2)). Sounds like you're fairly new to web dev, so just mark bower and npm as something to look at down the road. – gregmac Feb 24 '15 at 03:51
1

From your description, I believe it would require a color-space conversion from RGB to HSL (hue, saturation, lightness), change the lightness value to suit your needs and then convert back the new color to RGB. You can find the code here Wikipedia offers a good explanation on the HSL and HSV/HSB color spaces and their relationship with RGB color space

imelgrat
  • 1,557
  • 11
  • 16