0

I have an RGB based darken function that equally reduces the individual color channels by the given amount in percentage.

/**
 * Darkens the given RGB color by the specified amount.
 *
 * **NOTE:** The algorithm used to darken the given color is based on RGB,
 * so it will not return the exact same value as the Sass `darken` function, which is based on HSL lightness.
 * @param {{ r: number, g: number, b: number }} color - RGBFormat object representation of the color to darken.
 * @param {number} amount - (Must be 0-100) The percentage amount to decrease equally to each of the RGB color channels.
 */
export function darken(color, amount) {
    if (amount > 100) amount = 100;
    else if (amount < 0) amount = 0;

    const rgb = Object.assign({}, color); // copy so the object passed by reference is not mutated.
    for (const [key, value] of Object.entries(rgb)) {
        rgb[key] = Math.round(value * (1 - (amount / 100)));
    }

    return rgb;
}

For example,

If I have a color in HEX value #3498db, Sass darken(#3498db, 10%) wll give us #217dbb. Which is 10% darker in HSL Lightness.

But for JS function on the other hand, darken({r: 52, g: 152, b: 219}, 10) (This is the RGB equivalent of #3498db) will result to {r: 47, g: 137, b: 197} which is #2f89c5.

For now I am just using arbitrary ratio for the two darken amount's to approximate to what would seem to be the nearest result to the Sass darken.

Alex Pappas
  • 2,377
  • 3
  • 24
  • 48

0 Answers0