Home Programmatically Lighten or Darken a hex color (or rgb, and blend colors)
Reply: 0

Programmatically Lighten or Darken a hex color (or rgb, and blend colors)

user2518
1#
user2518 Published in May 24, 2018, 11:16 pm

Here is a function I was working on to programmatically lighten or darken a hex color by a specific amount. Just pass in a string like "3F6D2A" for the color (col) and a base10 integer (amt) for the amount to lighten or darken. To darken, pass in a negative number (i.e. -20).

The reason for me to do this was because of all the solutions I found, thus far, they seemed to over-complicate the issue. And I had a feeling it could be done with just a couple lines of code. Please let me know if you find any problems, or have any adjustments to make that would speed it up.

function LightenDarkenColor(col,amt) {
    col = parseInt(col,16);
    return (((col & 0x0000FF) + amt) | ((((col>> 8) & 0x00FF) + amt) << 8) | (((col >> 16) + amt) << 16)).toString(16);
}

For Development use here is an easier to read version:

function LightenDarkenColor(col,amt) {
    var num = parseInt(col,16);
    var r = (num >> 16) + amt;
    var b = ((num >> 8) & 0x00FF) + amt;
    var g = (num & 0x0000FF) + amt;
    var newColor = g | (b << 8) | (r << 16);
    return newColor.toString(16);
}

And finally a version to handle colors that may (or may not) have the "#" in the beginning. Plus adjusting for improper color values:

function LightenDarkenColor(col,amt) {
    var usePound = false;
    if ( col[0] == "#" ) {
        col = col.slice(1);
        usePound = true;
    }

    var num = parseInt(col,16);

    var r = (num >> 16) + amt;

    if ( r > 255 ) r = 255;
    else if  (r < 0) r = 0;

    var b = ((num >> 8) & 0x00FF) + amt;

    if ( b > 255 ) b = 255;
    else if  (b < 0) b = 0;

    var g = (num & 0x0000FF) + amt;

    if ( g > 255 ) g = 255;
    else if  ( g < 0 ) g = 0;

    return (usePound?"#":"") + (g | (b << 8) | (r << 16)).toString(16);
}

OK, so now it's not just a couple of lines, but it seems far simpler and if you're not using the "#" and don't need to check for colors out of range, it is only a couple of lines.

If not using the "#", you can just add it in code like:

var myColor = "3F6D2A";
myColor = LightenDarkenColor(myColor,10);
thePlaceTheColorIsUsed = ("#" + myColor);

I guess my main question is, am I correct here? Does this not encompass some (normal) situations?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.523272 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO