SVG 符号中的线性渐变



我有一个 svg 精灵<symbol>trhat 包含一个<linearGradient>.我正在以同一<symbol>提交一份<g>,其中包含fill="url(#id)"的梯度。但是,当我在其他文档中加载带有<use><symbol>时,<linearGradient>不会加载。我可以看到填充的 url 指的是绝对路由而不是文档内部,并且无法正确加载。

如何在<symbol>中加载<linearGradient>

<symbol viewBox="0 0 550 90" width="100%" height="100%">
<defs>
<linearGradient id="gradient">
<stop offset="-1.04974" stop-color="#D8D8D8">
<animate attributeName="offset" values="-2; 1" dur="1s" repeatCount="indefinite"></animate>
</stop>
<stop offset="-0.549739" stop-color="#EEEEEE">
<animate attributeName="offset" values="-1.5; 1.5" dur="1s" repeatCount="indefinite"></animate>
</stop>
<stop offset="-0.0497395" stop-color="#D8D8D8">
<animate attributeName="offset" values="-1; 2" dur="1s" repeatCount="indefinite"></animate>
</stop>
</linearGradient>
</defs>
<g fill="url(#gradient)">
<rect x="0" y="0" width="100" height="15"/> 
<rect x="10" y="25" width="130" height="15" />                              
</g>
</symbol>

对我来说,我的<svg>标签上有display: none,其中包含我的<defs><symbols>

确保初始 svg 没有设置display:none- 请改用height: 0; width: 0; position: absolute; visibility: hidden

另外,正如 Waruyama 的回答中所述,请确保<defs>不在<symbol>标签之外。

在这里找到这个提示。

正如评论中指出的,将linearGradient放在symbol之外。

下面是一个修改后的示例:

<svg style="visibility:hidden; width: 0; height: 0;">
<defs>
<linearGradient id="gradient">
<stop offset="-1.04974" stop-color="#D8D8D8">
<animate attributeName="offset" values="-2; 1" dur="1s" repeatCount="indefinite"></animate>
</stop>
<stop offset="-0.549739" stop-color="#EEEEEE">
<animate attributeName="offset" values="-1.5; 1.5" dur="1s" repeatCount="indefinite"></animate>
</stop>
<stop offset="-0.0497395" stop-color="#D8D8D8">
<animate attributeName="offset" values="-1; 2" dur="1s" repeatCount="indefinite"></animate>
</stop>
</linearGradient>
<symbol id="symbol1" viewBox="0 0 550 90" width="100%" height="100%">
<g fill="url(#gradient)">
<rect x="0" y="0" width="100" height="15"/> 
<rect x="10" y="25" width="130" height="15" />                              
</g>
</symbol>
</defs> 
</svg>
<svg width="400" height="400">
<use xlink:href="#symbol1"></use>
</svg>

最新更新