Search code examples
svg

Hide original when cloning element in SVG


I'm generating an SVG where I want to use an element as a stamp to create many similar elements.

This works well using <rect> and <use>, with one caveat: I want to hide my "tool" element (the original <rect>). How can I do this in SVG?

This is what my current SVG looks like:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg viewBox="0 0 500 500" xmlns="http://www.w3.org/2000/svg">
<rect id="blocked" width="20" height="20" stroke-width="1" stroke="#000000" fill="#000000" />
<use href="#blocked" x="20" y="100" />
<use href="#blocked" x="60" y="60" />
<use href="#blocked" x="60" y="100" />
</svg>

enter image description here

Here is a workaround, where I move the <rect> outside the viewbox, but then I have to compensate in the coordinates for the <use> tags.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg viewBox="0 0 500 500" xmlns="http://www.w3.org/2000/svg">
<rect id="blocked" width="20" height="20" x="-1000" y="-1000" stroke-width="1" stroke="#000000" fill="#000000" />
<use href="#blocked" x="1020" y="1100" />
<use href="#blocked" x="1060" y="1060" />
<use href="#blocked" x="1060" y="1100" />
</svg>


Solution

  • Make the original element a child of <defs>

    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <svg viewBox="0 0 500 500" xmlns="http://www.w3.org/2000/svg">
    <defs>
      <rect id="blocked" width="20" height="20" stroke-width="1" stroke="#000000" fill="#000000" />
    </defs>
    <use href="#blocked" x="20" y="100" />
    <use href="#blocked" x="60" y="60" />
    <use href="#blocked" x="60" y="100" />
    </svg>