Creative Coding with SVGs
zuubaDigital

use

codepen practice page

the use element

You don’t always have to create new shapes from scratch. It’s possible to re-use existing objects

The use element allows you to "copy" and reuse other svg elements.

1 2 3 4 5 6 7 8 <circle id="dot" cx="100" cy="100" r="100" fill="#C4C4C4" /> <use href="#dot" x="250" y="250"> </use>

reusable_use_intro.png

use attributes

  • href the id of the object being used - in this case, the circle element.
  • x, y The x and y attributes are required, and are used to set the position of the use element.

The confusing part: x and y don’t designate the actual position of the graphic. The x and y attributes set the position of the origin (the 0,0 point) of the <use> object’s coordinate system. The origin of the <use> object is set to the 250, 250 point of the svg’s coordinate system.

resuable_use_xy.png

You can also use presentation attributes to set the <use> element's appearance. You can’t override the original presentation attributes, but you can set them if they haven’t already been set.

In the example below, the stroke and stroke-width attributes have been set in the original element, so they can’t be changed in the <use> object. The fill attribute isn’t used in the original, so it can be set in the <use> element.

1 2 3 4 5 6 7 8 <circle id="dot" cx="100" cy="100" r="100" stroke="black" stroke-width="4" /> <use href="#dot" x="250" y="250" fill="#0DD9F4"/>

reusable_use_no_override.png

Attempts to override presentation attributes of the original are simply ignored by the browser.