【发布时间】:2019-03-21 23:39:42
【问题描述】:
我发现当我有一个带有符号的源 SVG 和一个使用 <use> 访问源 SVG 的目标 SVG 时,符号被导入并且能够访问渐变(可能是因为它已经在页)。但是,当源 SVG 位于不同的文件中时,会导入 <symbol> 中的对象,但不会导入渐变。 如何也导入渐变?
这是一些 MCVE 代码:
index.html:
<style>
html,body,svg { width: 100% }
</style>
<!-- inline SVG with gradient -->
<svg viewBox="0 0 80 20" xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<symbol id="myDot" width="10" height="10" viewBox="0 0 2 2">
<linearGradient id="linear-gradient" x1="0.133" y1="0.008" x2="0.949" y2="1.101" gradientUnits="objectBoundingBox">
<stop offset="0.042" stop-color="#21dbaa"/>
<stop offset="0.358" stop-color="#00b4ef"/>
<stop offset="0.433" stop-color="#01a7ec"/>
<stop offset="0.568" stop-color="#0487e4"/>
<stop offset="0.68" stop-color="#0768dd"/>
<stop offset="0.965" stop-color="#5f1ae5"/>
</linearGradient>
<circle cx="1" cy="1" r="1" fill="url(#linear-gradient)"/>
</symbol>
</svg>
<svg viewBox="0 0 200 60" xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- All instances of our symbol -->
<use xlink:href="#myDot" x="5" y="5" style="opacity:1.0" />
<use xlink:href="#myDot" x="20" y="5" style="opacity:0.8" />
<use xlink:href="symbol.svg#myDot" x="35" y="5" style="opacity:0.6" stroke="black" stroke-width=".1" />
<use xlink:href="symbol.svg#myDot" x="50" y="5" style="opacity:0.4" stroke="black" stroke-width=".1" />
<use xlink:href="symbol.svg#myDot" x="65" y="5" style="opacity:0.2" stroke="black" stroke-width=".1" />
</svg>
symbol.svg:
<!-- external SVG with gradient -->
<svg viewBox="0 0 80 20" xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<symbol id="myDot" width="10" height="10" viewBox="0 0 2 2">
<linearGradient id="linear-gradient" x1="0.133" y1="0.008" x2="0.949" y2="1.101" gradientUnits="objectBoundingBox">
<stop offset="0.042" stop-color="#21dbaa"/>
<stop offset="0.358" stop-color="#00b4ef"/>
<stop offset="0.433" stop-color="#01a7ec"/>
<stop offset="0.568" stop-color="#0487e4"/>
<stop offset="0.68" stop-color="#0768dd"/>
<stop offset="0.965" stop-color="#5f1ae5"/>
</linearGradient>
<circle cx="1" cy="1" r="1" fill="url(#linear-gradient)"/>
</symbol>
</svg>
这是一个说明问题的working Codepen demo,使用与上面相同的代码。注意从index.html 中的内联SVG 导入符号的两个圆圈如何正确显示渐变,但从symbol.svg 导入符号的三个圆圈没有显示渐变。
编辑:这可能与 another question 询问有关在外部文件中引用渐变的重复。
【问题讨论】:
-
如果将 linearGradient 元素放在符号元素之外,它应该可以在 Firefox 中使用。
-
@RobertLongson 嗯...那只是 Firefox 吗?是否有符合标准/交叉兼容的方法?我希望能支持 IE11+
-
对于 IE11 我想你可能需要这个:github.com/jonathantneal/svg4everybody
标签: html svg linear-gradients