Ever since I dabbled around css blend modes, I wanted to look into the math behind it.
Compositing in CSS
Compositing is combining separate visual elements into a single image. There have been 2 types of compositing techniques used in CSS so far.
When 2 pixels get combined, 4 subpixel regions are formed:
- Region where only source is present
- only destination is present
- both are present
- neither is present (always empty)
There are 12 of operators which decides the behaviour in these regions.
|Porter-Duff Operations (source S on backdrop B)|
|4||S over B||(0,S,B,S)||1||1 - αS|
|5||B over S||(0,S,B,B)||1 - αB||1|
|6||S in B||(0,0,0,S)||αB||0|
|7||B in S||(0,0,0,B)||0||αS|
|8||S out B||(0,S,0,0)||1 - αB||0|
|9||B out S||(0,0,B,0)||0||1 - αS|
|10||S atop B||(0,0,B,S)||αB||1 - αA|
|11||B atop S||(0,S,0,B)||1 - αB||αS|
|12||S xor B||(0,S,B,0)||1 - αB||1 - αS|
CSS is using the Souce over Backdrop operation (4th entry in the table above) for blend modes.
Color obtained from compositing source color Cs and backdrop color Cb is given by general Porter Duff equation:
co = αs x Fs x Cs + αb x Fb x Cb αo = αs x 1 + αb x (1 – αs)
Blending is the aspect of compositing that calculates the mixing of colors where the source element and backdrop overlap.
Cr = (1 - αb) x Cs + αb x B(Cb, Cs)
where B(Cb, Cs) is the blending function.
B(Cb, Cs) = Cs</td> </tr>