27

我一直在尝试将我的 SVG 图标外部化到一个文件中,并使用<svg><use xlink:href="file.svg#icon" /></svg>. 从理论上讲,这非常有效,但是不同的浏览器在渲染方面存在问题。<use>当在文件内部引用符号并直接打开 svg 文件的 url时,所有浏览器都能够正确呈现 svg 。

简而言之,linearGradient在引用标记中的符号时,是否有一种跨浏览器的方法可以让 SVG 充当元素的填充<svg><use/></svg>

我设置了一个 plunker 来演示这个问题: http ://plnkr.co/edit/feKvZ7?p=preview

简化后,标记如下所示:

<!DOCTYPE html>
    <html>
      <body>
        <h1>SVG sprite test</h1>
        <svg width="100" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
          <use xlink:href="icon.svg#icon" />
        </svg>
      </body>
    </html>

SVG 文件如下所示:

  <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
      <defs>
        <linearGradient id="gradient">
          <stop offset="0" stop-color="black" />
          <stop offset="1" stop-color="white" />
        </linearGradient>
      </defs>
      <symbol id="icon" viewBox="0 0 100 100">
        <circle cx="50" cy="50" r="40" stroke="black" fill="url(#gradient)" />
      </symbol>
    
      <use id="iconuse" xlink:href="#icon" width="100" height="100" />
    
    </svg>

这是它在不同浏览器中的样子: 不同浏览器中符号的线性渐变渲染结果不同

4

3 回答 3

0

也许尝试使用

<img src="name.svg">

于 2022-02-22T09:22:45.543 回答
0

symbol标签用于隐藏其中的元素。内部的元素通过其唯一指示符symbol使用命令调用。 因此,最好使用这种调用单个元素的方法而不是调用整体<use>
symbol

另外,元素在使用的时候<use>落入了shadow DOM,在某些情况下使用CSS就变得不可能
了所以最好把symbol里面的所有内部样式都删掉,直接赋值给use命令

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <defs>
    <linearGradient id="gradient">
      <stop offset="0" stop-color="black" />
      <stop offset="1" stop-color="white" />
    </linearGradient>
  </defs>
  <symbol  id="icon"  viewBox="0 0 100 100"> 
    <circle id="circle" cx="50" cy="50" r="40"   />
     <rect id="rect" x="100" y="10" width="100" height="100" />
  </symbol>

  <use class="iconuse" xlink:href="#circle" width="100" height="100" fill="url(#gradient)" stroke="black" />
     <use class="iconuse" xlink:href="#rect" width="100" height="100" fill="url(#gradient)" />
</svg>

于 2019-12-20T14:13:39.830 回答
0

尝试下一个(这是 Inkscape 提供渐变实现的方式):

<linearGradient id="gradient">
  <stop
     style="stop-color:black;"
     offset="0"/>
  <stop
     style="stop-color:white;"
     offset="1" />
</linearGradient>
...
<path
   style="fill:url(#gradient); ...
于 2017-05-29T06:30:45.927 回答