omgovich / colord

👑 A tiny yet powerful tool for high-performance color manipulations and conversions
https://colord.omgovich.ru
MIT License
1.63k stars 48 forks source link

Darken (or Lighten) By Percentage #86

Closed atb-brown closed 2 years ago

atb-brown commented 2 years ago

This is probably a lot simpler than I'm trying to make it, so forgive me if this is a dumb question, but how do I darken a colord by an arbitrary percentage?

myColor = colord("rgb(64, 128, 0)");
expect(myColor.darken(calculation).toRgbString()).toBe("rgb(32, 64, 0)");

In the above example, is there some way to reduce each RGB value by 50% (or any other arbitrary percent?

atb-brown commented 2 years ago

After some sleep, I've come up with the following solution, but would still be curious if there's a cleaner/easier approach.

const myColor = colord("rgb(64, 128, 0)");

const halfR = myColor.toRgb().r * 0.5;
const halfG = myColor.toRgb().g * 0.5;
const halfB = myColor.toRgb().b * 0.5;

const darkerColor = colord(`rgb(${halfR}, ${halfG}, ${halfB})`);

expect(darkerColor.toRgbString()).toEqual("rgb(32, 64, 0)"); // ✔
omgovich commented 2 years ago

Hi! I assume you can control lightness with HSL:

const { h, s, l } = colord("rgb(64, 128, 0)").toHsl()
colord({ h, s, l: l / 2 }).toRgbString()
atb-brown commented 2 years ago

@omgovich

control lightness with HSL

That works, thank you! I'll go ahead and close this. 🙂