Skip to content

Instantly share code, notes, and snippets.

@friday
Last active June 30, 2017 19:09
Show Gist options
  • Select an option

  • Save friday/9e73c668df172c836f93e900a888e9fb to your computer and use it in GitHub Desktop.

Select an option

Save friday/9e73c668df172c836f93e900a888e9fb to your computer and use it in GitHub Desktop.
Convert rgb(a) colors to hexadecimal
/**
* colorToHex: Convert rgb(a) or 3-6 letters hexadecimal color code to 6 letters code, with alpha-support.
* Uses an optional background parameter to control how colors with alpha channels are converted
*
* Not supported: color names such as "red", "green" (if you want to preserve those, then modify the function)
*
* Usage examples:
* colorToHex("#3F3") -> "#33ff33"
* colorToHex("rgba(255, 0, 0, 0.5)") -> "#ff8080"
* colorToHex("rgba(255,0,0,.5)", "rgb(0,255,0)") —> "#808000"
*/
function colorToHex(color, background) {
background = !background ? [255, 255, 255] : colorToHex(background)
.match(/(\w){2}/g)
.map(part => parseInt(part, 16));
const sanitized = (color || '').toLowerCase().replace(/[\s#]/g, '');
const format = parts => '#' + parts.map(part => ('0' + part.toString(16)).slice(-2)).join('');
if (/^([\da-f]{3}){1,2}$/.test(sanitized)) {
if (sanitized.length === 3) { // format 3 chars to 6
return '#' + sanitized.split('').map(char => char + char).join('');
}
return '#' + sanitized;
}
const matches = sanitized.match(/^rgba?\(([\d\.,]*)\)/);
if (matches) {
const parts = matches.pop().split(',');
const alpha = parts.length === 4 ? parseFloat(parts.pop()) : 1;
if (alpha !== 0 && parts.length === 3) {
return format(parts
.map(Number)
.map((decimal, index) => Math.round((decimal * alpha) + (background[index] * (1 - alpha))))
);
}
}
return format(background);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment