SVG fills in external file

2020-04-21 02:24发布

Really basic SVG question. I have read SVG sprite in external file and it works fine for me to add a svg graphic, but I can't get it to work with defs. First the file 'defs.svg':

 <svg  version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" >
    <defs id='patternDefs'>
          <pattern id="pattern1" 
            x="2" y="2"
            width="5" height="5"
            patternUnits="userSpaceOnUse" >
            <circle cx="2" cy="2" r="2" class="blue" />
        </pattern>
    </defs>
</svg>

and then the svg in a separate file:

<svg>
    <use xlink:href="defs.svg#patternDefs"></use>
        <circle cx="15" cy="15" r="50" stroke-width="2" stroke="red" fill="url(#pattern1)" />
</svg>

I am looking to get the fill="url(#pattern1)" part to work, as that is what is referencing the def in the external file.

Sorry if you think this has been answered elsewhere but I've read a ton of stuff and thought that if I could get the sprite version to work then why not a defs version. (I am very new to svg)

标签: svg
1条回答
等我变得足够好
2楼-- · 2020-04-21 02:53

xlink:href="defs.svg#patternDefs" should be xlink:href="defs.svg#pattern1"

On top of that <use> has to point to something to be rendered, not a pattern. If you want to fill a circle with a pattern just set the circle's fill to the pattern. E.g.

<svg>
    <circle cx="80" cy="80" r="50" stroke-width="2" stroke="red" fill="url(defs.svg#pattern1)" />
</svg>

Note that external fills are not widely supported, although they do work on Firefox for instance.

查看更多
登录 后发表回答