Skip to content

Instantly share code, notes, and snippets.

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