Porter-Duff Operators in SVG feComposite Filters

This article explains how the SVG <feComposite> filter primitive uses classical Porter-Duff compositing operators to combine two visual inputs at the pixel level. By manipulating the alpha channels and color values of source and destination graphics, developers can achieve precise masking, clipping, and layering effects natively within SVG.

Understanding Inputs in feComposite

The <feComposite> element operates on two image inputs defined by the in and in2 attributes:

Porter-Duff compositing calculates the output color (\(C\)) and opacity (\(\alpha\)) for every pixel based on the formula:

\[\text{Output} = \alpha_A \cdot F_A \cdot C_A + \alpha_B \cdot F_B \cdot C_B\]

Where \(F_A\) and \(F_B\) are weighting factors defined by the selected operator.


The Five Porter-Duff Operators in SVG

SVG defines five standard Porter-Duff operations via the operator attribute on <feComposite>:

1. over (Default)

Places the source graphic (\(A\)) on top of the destination graphic (\(B\)). Where the source is fully opaque, it completely covers the destination; where it is semi-transparent, the destination shows through.

<feComposite in="SourceGraphic" in2="BackgroundImage" operator="over" />

2. in

Renders only the parts of the source graphic (\(A\)) that overlap the opaque regions of the destination graphic (\(B\)). The destination graphic itself is not rendered.

<feComposite in="Texture" in2="SourceGraphic" operator="in" />

3. out

Renders only the parts of the source graphic (\(A\)) that fall outside the opaque regions of the destination graphic (\(B\)). Everything else, including the destination graphic, becomes transparent.

<feComposite in="ShapeA" in2="ShapeB" operator="out" />

4. atop

Renders the source graphic (\(A\)) only where the destination graphic (\(B\)) is opaque, while keeping the remaining non-overlapping parts of the destination graphic visible underneath.

<feComposite in="Highlight" in2="BaseShape" operator="atop" />

5. xor

Renders the regions where either the source (\(A\)) or destination (\(B\)) exists, but makes the overlapping regions where both are opaque completely transparent.

<feComposite in="ShapeA" in2="ShapeB" operator="xor" />

Alpha Channel Handling

Porter-Duff algorithms in <feComposite> rely on premultiplied alpha color spaces. Before computing output pixels, color channels (\(R, G, B\)) are multiplied by their respective alpha values. This ensures that anti-aliased edges and semi-transparent gradients blend smoothly without producing dark borders or color fringing artifacts.