是否可以在特定的绝对位置开始/停止SVG渐变?

3
我正在使用Javascript创建不同长度和位置的L形路径。我希望将线性渐变作为它们的描边,其中第一个停止偏移量位于x = 10像素处,即颜色变化始终在x像素之后发生。
通常,使用渐变的方式只提供相对定位(例如相对于对象边界框)。这会导致由于不同的对象边界框而产生不同的停止偏移量。
以下是一个示例:

  path.p1 {
    fill: none;
    stroke-width: 20px;
  }
<svg height="600" width="1000">


  <path class="p1" d="M10 10 V 100 H 100 " stroke="url(#cl1)"/>
  <path class="p1" d="M150 10 V 100 H 200 " stroke="url(#cl1)"/>
  <path class="p1" d="M250 10 V 100 H 400 " stroke="url(#cl1)"/>

    <defs>
        <linearGradient id="cl1" gradientUnits="objectBoundingBox" x1="0%" y1="0%" x2="100%" y2="0%">
            <stop offset="0" style="stop-color:grey;stop-opacity:1" />
            <stop offset="0.02" style="stop-color:grey;stop-opacity:1" />
            <stop offset="0.15" style="stop-color:orange;stop-opacity:1" />
            <stop offset="0.2" style="stop-color:orange;stop-opacity:1" />
        </linearGradient>
    </defs>
  
</svg>

有没有一种方法可以通过SVG嵌套或JavaScript巧妙地引用同一个渐变?
1个回答

5
请使用gradientUnits="userSpaceOnUse"。这样,渐变色将以绝对单位的方式定位,但始终在定义它的元素的本地坐标系中。
在您的情况下,使所有路径处于相同的坐标系中意味着您定义了一个跨越所有路径的总体渐变。为了避免这种情况,您需要进行更改,例如通过定义transform属性。每个连续路径都向右移动更多,而其起点(在本地坐标系中测量)保持在原地。

  path.p1 {
    fill: none;
    stroke-width: 20px;
  }
<svg height="600" width="1000">


  <path class="p1" d="M10 10 V 100 H 100 " stroke="url(#cl1)"/>
  <path class="p1" d="M10 10 V 100 H 60 " stroke="url(#cl1)" transform="translate(140)"/>
  <path class="p1" d="M10 10 V 100 H 160 " stroke="url(#cl1)" transform="translate(240)"/>

    <defs>
        <linearGradient id="cl1" gradientUnits="userSpaceOnUse" x1="10" y1="0" x2="110" y2="0">
            <stop offset="0" style="stop-color:grey;stop-opacity:1" />
            <stop offset="0.02" style="stop-color:grey;stop-opacity:1" />
            <stop offset="0.15" style="stop-color:orange;stop-opacity:1" />
            <stop offset="0.2" style="stop-color:orange;stop-opacity:1" />
        </linearGradient>
    </defs>
  
</svg>


1
但是现在还没有办法以像素为单位指定停止偏移量,对吧?这就是我现在需要的,控制停止偏移值的能力,就像“userSpaceOnUse”一样。 - Sideways S
没有,参见规范 - ccprog

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