Convert RGBA to HEX

Michael Böckling picture Michael Böckling · Feb 5, 2014 · Viewed 57.1k times · Source

Given a css color value like:

 rgba(0, 0, 0, 0.86)

How do I convert that to a RGB hex value that takes the alpha component into account, assuming a white background?

Answer

Marco A. picture Marco A. · Feb 5, 2014

Since alpha value both attenuates the background color and the color value, something like this could do the trick:

function rgba2rgb(RGB_background, RGBA_color)
{
    var alpha = RGBA_color.a;

    return new Color(
        (1 - alpha) * RGB_background.r + alpha * RGBA_color.r,
        (1 - alpha) * RGB_background.g + alpha * RGBA_color.g,
        (1 - alpha) * RGB_background.b + alpha * RGBA_color.b
    );
}

(Try it interactively: https://marcodiiga.github.io/rgba-to-rgb-conversion)