Samurai Jack
Samurai Jack

Reputation: 3135

Change color hex to darker

I know there is an answer to this (Programmatically darken a Hex colour), I already tried to follow that explanation.

So, I'm saving into a variable the value of a hex:

let y = chart.color(x);

If I'm printing it, it looks like this #1f77b4. So I delete the first character:

y = y.substr(1);

Now it looks like this: 1f77b4 so I'm adding 0x at the begining:

y = "0x" + y; => now it is 0x1f77b4. Great!

And now I'm trying to make the color darker by using the method explained on that question:

y = (y & 0xfefefe) >> 1;

After this computation, y is 998234, converting it into hex makes it 7f3f07. I tried both these values but they are not darker blue.

The origin color was blue, I used this method to get a darker blue but I've got a brownish yellow instead.

Is something wrong in my solving?

Upvotes: 0

Views: 286

Answers (1)

Andrew Morton
Andrew Morton

Reputation: 25057

It appears that your (unshown) function used to convert to a hex string is not working correctly. Fortunately, JavaScript's toString function for numbers has an optional parameter which will do the conversion for you.

Also, as you're using the result in HTML/JavaScript, you may need prepend zeros to a width of 6, so...

function halveBrightness(hexColor) {
    if (hexColor.charAt(0) == "#") {
        hexColor = hexColor.substr(1);
    }
    var color = parseInt(hexColor, 16);
    /* using the method of https://stackoverflow.com/a/1787193/1115360 */
    color = (color & 0xFEFEFE) >> 1;

    return padLeft("0", 6, color.toString(16));

}

function padLeft(padChar, finalLength, str) {
    padChar = padChar.charAt(0);
    var nPads = finalLength - str.length;
    var padding = "";
    for(var i=1; i<=nPads; i++) {
        padding += padChar;
    }

    return padding + str;
}

/* using the value from the question */
var y = "#1f77b4";
console.log(halveBrightness(y));

/* check it works when bytes are/will become zero */
console.log(halveBrightness("0001FF"));

Outputs:

0f3b5a
00007f

You may need to put a "#" or "0x" at the beginning of the result, depending on what you're using it for.

Upvotes: 1

Related Questions