2D SDF composition
Build a shape from signed distances combined with min, max and smooth min, then draw fill, stroke and shadow from the result.
Cards
One live example to tweak, learn and copy.
How it works
A signed distance fieldA function that returns how far a point is from the edge of a shape, negative inside and positive outside. Zero is the outline itself. Signed distance field (SDF) A function that returns how far a point is from the edge of a shape, negative inside and positive outside. Zero is the outline itself. Smooth minimum A version of min that rounds the corner where two values cross. Applied to two distance fields it melts the shapes into one, with the blend width set by k.circle(p) = |p| − rmin of two fields is both shapes at once (a union),
the max is only where they overlap (an intersection), and max(a, -b) is the first shape with the second cut out of
it (a subtraction). A smooth minimumA version of min that rounds the corner where two values cross. Applied to two distance fields it melts the shapes into one, with the blend width set by k.h = clamp(0.5 + 0.5 (b − a) / k, 0, 1); smin = mix(b, a, h) − k h (1 − h)
So a complex shape doesn’t need its own formula. A rounded rectangle is a box whose distance has been shrunk and grown back; a chevron is two line segments in a union; a ring is a disc minus a smaller disc. The result is still a distance field, so the next step can use it the same way.
That is what makes composition worth learning. One distance gives you several looks for free: the fill (below zero),
a stroke (near zero from either side), a glow or a soft drop shadow (a wide smoothstep outside), each one an edge cut
from the same number. And because the edge is cut from a distance, it can be anti-aliased exactly, one pixel wide at
any size, with the screen-space derivative fwidth. UI elements, icons, map markers and font glyphs are drawn this
way when they must stay sharp at any zoom.
Further reading
- dFdx, dFdy (opens in a new tab)Reference
- fwidth (opens in a new tab)Reference
- Filterable procedurals (opens in a new tab)Article
- 2D distance functions (opens in a new tab)Article
- Signed distance function (opens in a new tab)Reference
- Shapes (opens in a new tab)Book
- Smooth minimum (opens in a new tab)Article
- Distance functions (opens in a new tab)Article
- Distance functions (opens in a new tab)Article
- Improved alpha-tested magnification for vector textures and special effects (opens in a new tab)Paper
- CanvasItem shaders (opens in a new tab)Docs