scttcper/tinycolor

Add a function to compute how a semi-transparent color would appear on a background

ariasuni opened this issue · 2 comments

The other day I wanted to compute the contrast between two colors but the luminance and hence the readability function doesn’t take the alpha canal into account: one need to know the “final” color, in other words what’s the color is on its background, to compute the contrast.

There are probably other uses for being able to compute how a color would appear on a background, and it’s very short to implement. It’s also easy to get it wrong, so I think it makes sense to have a correct and checked implement in a library like this one.

The implementation could simply be (if you’re interested I can make a PR):

onBackground(background: ColorInput): TinyColor {
  const fg = this.toRgb();
  const bg = new TinyColor(background).toRgb();

  return new TinyColor({
    r: bg.r + (fg.r - bg.r) * fg.a,
    g: bg.g + (fg.g - bg.g) * fg.a,
    b: bg.b + (fg.b - bg.b) * fg.a,
  })
}

I also though of rgbaToRgb as a function name but that may be confusing with all the other function with rgb in their names I guess.

Adapted from this StackOverflow answer.

I'd be open to a pr

🎉 This issue has been resolved in version 3.2.0 🎉

The release is available on:

Your semantic-release bot 📦🚀