Embed SVG in SVG?

Use the image element and reference your SVG file. For fun, save the following as recursion.svg:

<svg width="100%" height="100%" viewBox="-100 -100 200 200" version="1.1"
     xmlns="http://www.w3.org/2000/svg">
  <circle cx="-50" cy="-50" r="30" style="fill:red" />
  <image x="10" y="20" width="80" height="80" href="recursion.svg" />
</svg>

Or you can actually embed child svg in parent svg like this:

<svg>
    <g>
        <svg>
            ...
        </svg>
    </g>
</svg>

demo:
http://hitokun-s.github.io/old/demo/path-between-two-svg.html


It is worth mentioning that when you embed SVGs into another SVG with:

<image x="10" y="20" width="80" height="80" xlink:href="image.svg" />

then the embedded SVG takes a rectangular shape with given dimensions.

That is to say, if your embedded SVG is a circle or some shape other than a square, then it becomes a square with transparency. Therefore, mouse events get trapped into that embeded square and do not reach the parent SVG. Watch out for that.

A better approach is using a pattern. To fill a shape, either a circle, a square or even a path.

<defs>
 <pattern id="pat" x="0" y="0" width="500" height="500" patternUnits="userSpaceOnUse">
   <image x="0" y="0" width="500" height="500" xlink:href="images/mysvg.svg"></image>
 </pattern>
</defs>

Then use the pattern like this:

<circle cx="0" cy="0" r="250" fill="url(#pat)"></circle>

Now your mouse events do not get stuck into transparent image squares!

Tags:

Xml

Svg

Embedding