Display external SVG with <use> tag and href or xlink:href attribute?

让人想犯罪 __ 提交于 2021-02-11 09:46:34

问题


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:


  1. You have this error: Unsafe attempt to load URL https:.....svg from frame with URL https://...... Domains, protocols and ports must match

  2. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!