Skip to content

Instantly share code, notes, and snippets.

@oleggrishechkin
Created November 24, 2020 16:28
Show Gist options
  • Save oleggrishechkin/14b028bb6a98ea7f72f15eb68258e925 to your computer and use it in GitHub Desktop.
Save oleggrishechkin/14b028bb6a98ea7f72f15eb68258e925 to your computer and use it in GitHub Desktop.
const colorToHEX = (colorString) => {
if (colorString.startsWith('rgba(')) {
const rgba = colorString
.slice(5, colorString.length - 1)
.split(',')
.map((item) => +item.trim());
const background = [255, 255, 255];
const hex = [
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)
].map((item) => `0${item.toString(16)}`.slice(-2));
return `#${hex[0]}${hex[1]}${hex[2]}`;
}
if (colorString.startsWith('rgb(')) {
const rgb = colorString
.slice(4, colorString.length - 1)
.split(',')
.map((item) => +item.trim());
const hex = rgb.map((item) => `0${item.toString(16)}`.slice(-2));
return `#${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