Skip to content

Instantly share code, notes, and snippets.

@oleggrishechkin
Created November 24, 2020 16:28
Show Gist options
  • Save oleggrishechkin/9c5b1643d76417891f17c8bd580d6588 to your computer and use it in GitHub Desktop.
Save oleggrishechkin/9c5b1643d76417891f17c8bd580d6588 to your computer and use it in GitHub Desktop.
const colorToRGBA = (colorString, alpha) => {
if (colorString.startsWith('rgb(')) {
const rgb = colorString
.slice(4, colorString.length - 1)
.split(',')
.map((item) => +item.trim());
return `rgba(${rgb[0]}, ${rgb[1]}, ${rgb[2]}, ${alpha})`;
}
if (colorString.startsWith('#')) {
const hex = [colorString.slice(1, 3), colorString.slice(3, 5), colorString.slice(5, 7)].map((item) =>
parseInt(item, 16)
);
return `rgba(${hex[0]}, ${hex[1]}, ${hex[2]}, ${alpha})`;
}
return colorString;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment