Skip to content

Instantly share code, notes, and snippets.

@Gummiees
Created October 29, 2020 09:35
Show Gist options
  • Save Gummiees/7be8aa7b45a1a89b66b5e424a4bebabe to your computer and use it in GitHub Desktop.
Save Gummiees/7be8aa7b45a1a89b66b5e424a4bebabe to your computer and use it in GitHub Desktop.
Convert hexadecimal color to RGBA with transparency
/** Converts hexadecimal color to RGBA with transparency. */
public transparentize(color: string, opacity: number = 0.5): string {
return this.hexToRgbA(color, 1 - opacity);
}
/** Converts an hexadecimal color to RGBA */
public hexToRgbA(hex: string, opacity: number = 1): string {
let c: any;
if (/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)) {
c = hex.substring(1).split('');
if (c.length === 3) {
c = [c[0], c[0], c[1], c[1], c[2], c[2]];
}
c = `0x${c.join('')}`;
return `rgba(${[(c >> 16) & 255, (c >> 8) & 255, c & 255].join(',')}, ${opacity})`;
}
throw new Error('Bad Hex');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment