Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature request] Rgba to rgb conversion fuction #581

Open
aleksandrlat opened this issue May 18, 2021 · 1 comment
Open

[Feature request] Rgba to rgb conversion fuction #581

aleksandrlat opened this issue May 18, 2021 · 1 comment

Comments

@aleksandrlat
Copy link

aleksandrlat commented May 18, 2021

Summary

Add function to convert Rgba to Rgb

Basic Example

function rgbaToRgb(rgbaColor: string, bgColor: string = '#fff') {
  const rgba = parseToRgb(rgbaColor)
  const bg = parseToRgb(bgColor)

  const flattenedColor = {
    red: rgba.alpha * rgba.red + (1 - rgba.alpha) * bg.red,
    green: rgba.alpha * rgba.green + (1 - rgba.alpha) * bg.green,
    blue: rgba.alpha * rgba.blue + (1 - rgba.alpha) * bg.blue,
  }

  return rgbToColorString(flattenedColor)
}

Or maybe it should be lightenToOpacity?

function lightenToOpacity(color: string, opacity: number, bgColor: string = 'white') {
  // ....
}

Reasoning

Designer asked to make rgba(primaryColor, 0.1) but I have to set it as background color and it cannot have opacity because there is another element behind it.
So I need to make non transparent color.

I cannot use lighten or setLightness because I don't know required lightness. I know only opacity.

This link was useful for me https://filosophy.org/code/online-tool-to-lighten-color-without-alpha-channel/

@aleksandrlat aleksandrlat changed the title Rgba to rgb conversion fuction [Feature request] Rgba to rgb conversion fuction May 18, 2021
@ChaseBro
Copy link

should probably include a Math.round to wrap the math, otherwise you can end up with wonky hex values as it tries to deal with floating point values in the RGB channels. i.e.:

  const flattenedColor = {
    red: Math.round(rgba.alpha * rgba.red + (1 - rgba.alpha) * bg.red),
    green: Math.round(rgba.alpha * rgba.green + (1 - rgba.alpha) * bg.green),
    blue: Math.round(rgba.alpha * rgba.blue + (1 - rgba.alpha) * bg.blue),
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants