Skip to content

Instantly share code, notes, and snippets.

@BirgitPohl
Created October 3, 2022 18:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BirgitPohl/2a76c6f5d9a47f7f753190f2329d693e to your computer and use it in GitHub Desktop.
Save BirgitPohl/2a76c6f5d9a47f7f753190f2329d693e to your computer and use it in GitHub Desktop.
Hexadecimal to RGBA
/**
* @param hex HexColor #000000 #000
* @param opacity 0-100
* @returns `rgba(RR, GG, BB, 0.x)`
*/
export const hexToRgbA = <T extends string>(hex: HexColor<T>, opacity: number): T => {
let c;
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(${[(parseInt(c) >> 16)&255, (parseInt(c) >> 8)&255, parseInt(c)&255].join(',')}, ${opacity / 100})` as T;
}
throw new Error('Bad Hex');
};
type HexDigit = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | 'a' | 'b' | 'c' | 'd' | 'e'| 'f' | 'A' | 'B' | 'C' | 'D' | 'E'| 'F';
export type HexColor<T extends string> =
T extends `#${HexDigit}${HexDigit}${HexDigit}${infer Rest1}`
? (Rest1 extends string
? T // three-digit hex color
: (
Rest1 extends `#${HexDigit}${HexDigit}${HexDigit}`
? T // six-digit hex color
: string
)
)
: string;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment