Search code examples
mathcolorsshaderpixelalphablending

How does alpha blending work, mathematically, pixel-by-pixel?


Seems like it's not as simple as RGB1*A1 + RGB2*A2...how are values clipped? Weighted? Etc.

And is this a context-dependent question? Are there different algorithms, that produce different results? Or one standard implementation?

I'm particularly interested in OpenGL-specific answers, but context from other environments is useful too.


Solution

  • I don't know about OpenGL, but one pixel of opacity A is usually drawn on another pixel like so:

    result.r = background.r * (1 - A) + foreground.r * A
    result.g = background.g * (1 - A) + foreground.g * A
    result.b = background.b * (1 - A) + foreground.b * A
    

    Repeat this operation for multiple pixels.