具有不同渐变颜色的可重用 SVG

Reusable SVG with different gradient colors

根据我的要求,我需要形状路径,我需要在其中应用不同的渐变颜色。举个例子,我正在绕圈并尝试做同样的事情。

代码如下:

.box--blue{
  fill: blue;
}

.box--red{
  fill: red;
}
<div>
  <svg>
    <defs>
      <linearGradient id="Gradient2" x1="0" x2="0" y1="0" y2="1">
        <stop offset="0%" stop-color="transparent"/>
        <stop offset="100%" stop-color="blue"/>
      </linearGradient>
    </defs>
    <symbol id="gra2" viewbox="0 0 100 100">
  
  <circle cx="50" cy="50" r="50" fill="url(#Gradient2)" />
    </symbol>
</svg>
</div>


<div class="box box--red">
  <svg>
    <use xlink:href="#gra2"></use>
  </svg>
</div>

<div class="box box--blue">
  <svg>
    <use xlink:href="#gra2"></use>
  </svg>
</div>

要求:

通过重用可用的 SVG,我需要这两个具有不同颜色的渐变形状。

浏览器支持:IE10+、chrome 和 Firefox。

注意:我不想在 SVG 下对每个颜色相关的渐变进行硬编码。渐变色应该可以继承。这就是我如何重用 SVG,IMO。

你想要的不可能。

我认为最接近的是使用特殊颜色 currentColor 将 CSS color 的当前值传递给符号。您可以将它传递给符号,但不能传递给渐变。所以你需要用它来给一个圆圈上色。然后在上面放一个渐变。但是,在此解决方案中,圆圈显然不能像您的示例那样部分透明。

.box--blue {
  color: blue;
}

.box--red {
  color: red;
}
<div>
  <svg>
    <defs>
      <linearGradient id="Gradient2" x1="0" x2="0" y1="0" y2="1">
        <stop offset="0%" stop-color="white"/>
        <stop offset="100%" stop-color="transparent"/>
      </linearGradient>
    </defs>
    <symbol id="gra2" viewbox="0 0 100 100">
      <circle cx="50" cy="50" r="50" fill="currentColor" />
      <circle cx="50" cy="50" r="50" fill="url(#Gradient2)" />
    </symbol>
</svg>
</div>


<div class="box box--red">
  <svg>
    <use xlink:href="#gra2"></use>
  </svg>
</div>

<div class="box box--blue">
  <svg>
    <use xlink:href="#gra2"></use>
  </svg>
</div>