问题
The SVG is not display correctly when it is loaded from <use>
tag. I've added an img tag to illustrate the expected result.
Code sample:
<svg>
<use xlink:href="file.svg" href="file.svg"></use>
</svg>
<img src="file.svg" />
Current output:
Working fiddle: demo
Thank to anyone who can point out my mistake.
回答1:
You have this error: Unsafe attempt to load URL https:.....svg from frame with URL https://...... Domains, protocols and ports must match
You need to use the id of the svg object you want to use
<svg viewBox="0 0 14 16" width="50">
<use xlink:href="sof.svg#id" fill="red"/>
</svg>
Please take a look at this example: https://codepen.io/enxaneta/project/editor/91143c063e6b9abf1b5c43a14a9937ea
回答2:
The <use>
element does copy an Element that you do link to from the href
attribute. You can not point to a file.svg
directly, you need to point to the id
of an element.
<use xlink:href="path/to-the-file.svg#the-element"/>
// since we can't store file in StackSnippets we'll download it first
fetch('https://upload.wikimedia.org/wikipedia/commons/f/fd/Ghostscript_Tiger.svg')
.then(r => r.blob())
.then(b =>
// and create a blobURI, with the id of a <g> Element
use.setAttributeNS(
'http://www.w3.org/1999/xlink', 'href',
URL.createObjectURL(b) + '#g4'
)
);
<svg width="200" height="200" viewBox="0 0 900 900">
<use id="use"/>
</svg>
But note that the <image> element could also have displayed your image directly (even though you'll loose the little control you may have from <use>:
<svg width="200" height="200" viewBox="0 0 200 200">
<image width="200" height="200" xlink:href="https://upload.wikimedia.org/wikipedia/commons/f/fd/Ghostscript_Tiger.svg"/>
</svg>
来源:https://stackoverflow.com/questions/53794292/display-external-svg-with-use-tag-and-href-or-xlinkhref-attribute