Home > database >  Why tinycolor().brighten() is not working correctly?
Why tinycolor().brighten() is not working correctly?

Time:02-01

I am using tinycolor2, I want to get brighter colors from brandColor_Base this is how my code looked like

import tinycolor from "tinycolor2"

const brandColor_Base="#338EF5";

export var  colors={
    
    brandColor_1:tinycolor(brandColor_Base).brighten(70).toString(),
    brandColor_2:tinycolor(brandColor_Base).brighten(55).toString(),
    brandColor_3:tinycolor(brandColor_Base).brighten(40).toString(),
    brandColor_4:tinycolor(brandColor_Base).brighten(25).toString(),
    brandColor_5:tinycolor(brandColor_Base).brighten(10).toString(),
    brandColor_6:tinycolor(brandColor_Base),
}

but because I won't to re-write each time tinycolor(brandColor_Base) I updated my code like below

import tinycolor from "tinycolor2"

const brandColor_Base=tinycolor("#338EF5");

export var  colors={
    
   brandColor_1:brandColor_Base.brighten(70).toString(),
   brandColor_2:brandColor_Base.brighten(55).toString(),
   brandColor_3:brandColor_Base.brighten(40).toString(),
   brandColor_4:brandColor_Base.brighten(25).toString(),
   brandColor_5:brandColor_Base.brighten(10).toString(),
   
}

this code is not working well, it is working like brandColor_5 is brighter than brandColor_4 and brandColor_4 is brighter than brandColor_3 etc and not brighter than brandColor_base (each time i remove one of previous line of code brandColor_5 is getting darker) what should I do ?

CodePudding user response:

That happens because brandColor_Base.brighten(70) doesn't return a new tinycolor instance, but instead mutates the existing instance.

In my opinion, this is bad API design of the tinycolor package.

brandColor_Base.brighten(70)
brandColor_Base.brighten(70)

Basically brightens the base color then brightens the result of that color again.

You can fix the issue by changing brandColor_Base to be a function:

import tinycolor from "tinycolor2"

const brandColor_Base = () => tinycolor("#338EF5");

export var colors = {
   brandColor_1: brandColor_Base().brighten(70).toString(),
   brandColor_2: brandColor_Base().brighten(55).toString(),
   brandColor_3: brandColor_Base().brighten(40).toString(),
   brandColor_4: brandColor_Base().brighten(25).toString(),
   brandColor_5: brandColor_Base().brighten(10).toString(),
}

brandColor_Base() will return a fresh tinycolor instance on each invocation.

You could change brandColor_Base() to accept brightness as a parameter and use it like this:

import tinycolor from "tinycolor2"

const brandColor_Base = (brightness) => {
   return tinycolor("#338EF5").brighten(brightness)
}

export var colors = {
   brandColor_1: brandColor_Base(70).toString(),
   brandColor_2: brandColor_Base(55).toString(),
   brandColor_3: brandColor_Base(40).toString(),
   brandColor_4: brandColor_Base(25).toString(),
   brandColor_5: brandColor_Base(10).toString(),
}
  • Related