Creative Coding with SVGs
zuubaDigital

defs

codepen practice page

the defs element

While it’s acceptable to use a visible object, the better practice is to define reusable objects in the defs section. You can think of defs as a storage place for graphical objects. Elements defined in defs aren’t rendered directly - they are only rendered when referred to by the use element.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 <svg width="500" height="500" viewbox="0 0 500 500"> <defs> <circle id="dot" cx="0" cy="0" r="100" fill="purple" /> </defs> <use href="#dot" x="250" y="250"> </use> </svg>

A defs object can be a single shape element like a circle, rectangle, or a path, or it can be multiple elements that are grouped <g>.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 <svg width="500" height="500" viewbox="0 0 500 500"> <defs> <circle id="dot" cx="0" cy="0" r="100" fill="purple" /> </defs> <use href="#dot" x="250" y="250"> </use> </svg>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 <svg width="500" height="500" viewbox="0 0 500 500"> <defs> <g id="smiley-face"> <circle cx="118.5" cy="140.5" r="12.5" fill="black" /> <circle cx="243.5" cy="140.5" r="12.5" fill="black" /> // more code </g> </defs> <use href="#smiley-face" x="0" y="0"> </use> </svg>