Skip to content

Instantly share code, notes, and snippets.

@khasky
Created Jun 2, 2021
Embed
What would you like to do?
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