GLSL Learning

GLSL shader example

Rounded Rectangle

A rounded rectangle SDF with fill and outline, the building block for buttons and UI cards in shaders.

Live example

Edit the code and the preview updates as you type.

How it works

sdRoundedBox returns the signed distance from a pixel to the rectangle's edge, just like length(p) - r does for a circle. Three tricks make it work:

  • abs(p) folds all four quadrants onto one, so the function only has to handle the top-right corner.
  • abs(p) - b + r measures how far the pixel sticks out past a smaller box. Outside that box, length(max(q, 0.0)) is the distance to its corner, which is what makes the corner round.
  • Subtracting r at the end grows that small box back out by the corner radius.

Because it is a distance, the same value gives you both shapes: d < 0 is the fill, and abs(d) < 0.02 is a thin band along the edge, which becomes the outline.

Try changing it

ChangeResult
vec2(0.7, 0.45) to vec2(0.5)A rounded square
radius to 0.45A pill shape: the corners meet in the middle
0.02 to 0.06A thicker outline
Remove the fill lineOnly the outline is drawn

Built-in functions used

Learn it step by step