线/矩的渐变边缘

时间:2016-05-20 01:47:21

标签: svg

我有一个svg <g>,其中我有一条线(也可以是矩形......已经尝试过两者)。该内部元素具有可以从8种不同颜色或图案旋转的填充/笔划。形状是5px高度,具有动态宽度,我应该支持淡化左,右或两个边缘。

我想在没有在svg上创建额外元素的情况下实现这一点,以及如何应用掩码/渐变,但似乎我无法使其工作。

由于形状的X和Y,颜色和宽度可以改变,我没有找到一种一致的方法来实现这一点,而无需使用一堆颜色组合创建新元素。有没有人知道如何以最简单和可扩展的方式实现这一目标?

UPDATE 在保罗建议之后,我创造了一个小提琴来代表我的场景: https://jsfiddle.net/0tnc9mq5/

所以多行/反映在同一个svg中,具有不同的颜色,位置和尺寸。将一些这些淡化应用于其中一些元素的方法是什么?我将如何实施保罗的建议?还有其他方法吗?

由于

1 个答案:

答案 0 :(得分:0)

这是一种方法,使用蒙版产生渐变结束。在此示例中,淡入淡出量固定为行长度的10%。

我们创建了一个共享SVG,其中包含您需要的三种变体中的每一种的<symbol>个元素。只需要在HTML中出现一次。

然后您想要其中一个分隔符,包括与所需分隔符对应的迷你SVG。您可以使用CSS设置分隔符的宽度,高度和颜色。

&#13;
&#13;
svg.sep {
  width: 500px;
  height: 5px;
}

.one {
  color: red;
}

.two {
  color: green;
}

.three {
  color: blue;
}
&#13;
<svg width="0" height="0" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <defs>
    <linearGradient id="gleft">
      <stop offset="0%" stop-color="black"/>
      <stop offset="10%" stop-color="white"/>
    </linearGradient>
    <linearGradient id="gright">
      <stop offset="90%" stop-color="white"/>
      <stop offset="100%" stop-color="black"/>
    </linearGradient>
    <linearGradient id="gboth">
      <stop offset="0%" stop-color="black"/>
      <stop offset="10%" stop-color="white"/>
      <stop offset="90%" stop-color="white"/>
      <stop offset="100%" stop-color="black"/>
    </linearGradient>
    
    <mask id="mleft">
      <rect width="1" height="1" fill="url(#gleft)"/>
    </mask>
    <mask id="mboth">
      <rect width="1" height="1" fill="url(#gboth)"/>
    </mask>
    <mask id="mright">
      <rect width="1" height="1" fill="url(#gright)"/>
    </mask>

    <symbol id="left" viewBox="0 0 1 1" preserveAspectRatio="none">
      <rect width="1" height="1" fill="currentColor" mask="url(#mleft)"/>
    </symbol>
    <symbol id="both" viewBox="0 0 1 1" preserveAspectRatio="none">
      <rect width="1" height="1" fill="currentColor" mask="url(#mboth)"/>
    </symbol>
    <symbol id="right" viewBox="0 0 1 1" preserveAspectRatio="none">
      <rect width="1" height="1" fill="currentColor" mask="url(#mright)"/>
    </symbol>
  </defs>
</svg>


<p> Lorem ipsum dolor sit</p>

<svg viewBox="0 0 1 1" preserveAspectRatio="none" class="sep one">
  <use xlink:href="#left"/>
</svg>

<p> Lorem ipsum dolor sit</p>

<svg viewBox="0 0 1 1" preserveAspectRatio="none" class="sep two">
  <use xlink:href="#right"/>
</svg>

<p> Lorem ipsum dolor sit</p>

<svg viewBox="0 0 1 1" preserveAspectRatio="none" class="sep three">
  <use xlink:href="#both"/>
</svg>
&#13;
&#13;
&#13;

相关问题