Skip to content

Instantly share code, notes, and snippets.

@khasky
Created June 2, 2021 17:01
Show Gist options
  • Save khasky/89dee020c5be8c18f66aa8ec9a16a8ec to your computer and use it in GitHub Desktop.
Save khasky/89dee020c5be8c18f66aa8ec9a16a8ec to your computer and use it in GitHub Desktop.
TypeScript RGBA to RGB
interface RGBAtoRGBOptions {
toColorRGBA: string;
backgroundColorRGB?: string;
}
function rgbaToRgb({ toColorRGBA, backgroundColorRGB = 'rgb(255,255,255)' }: RGBAtoRGBOptions) {
const [r, g, b, a] = toColorRGBA
.replace(/rgba|\(|\)/g, '')
.split(',')
.map((str) => parseInt(str, 2));
const [bgR, bgG, bgB] = backgroundColorRGB
.replace(/rgb|\(|\)/g, '')
.split(',')
.map((str) => parseInt(str, 2));
const r3 = Math.round((1 - a) * bgR + a * r);
const g3 = Math.round((1 - a) * bgG + a * g);
const b3 = Math.round((1 - a) * bgB + a * b);
return `rgb(${r3},${g3},${b3})`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment