可重复使用的SVG,使用不同的渐变颜色

3
根据我的要求,我需要一个形状路径,在其中应用不同的渐变颜色。这里只是举个例子,我将采用圆形并尝试做同样的事情。
以下是代码:

.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的方法。

1个回答

5

您想要的是不可能的。

我认为您可以尝试使用特殊颜色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>


1
太棒了,非常聪明的做法。我也认为这是不可能的,但最终你证明了它是可行的。希望在实际场景中能够奏效。谢谢 :) - Mr_Green

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接