是否可以在某个绝对位置开始/停止 SVG 渐变?

ee2*_*Dev 3 javascript svg gradient

我在 Javascript 中创建不同的 L 形路径。它们的长度和位置不同。我想有一个 linearGradient 作为它们的笔触,其中第一个停止偏移位于 x=10 像素的位置,即颜色的变化总是在 x 像素之后开始。

使用渐变的标准方式只是提供相对定位(例如,对象边界框)。由于不同的对象边界框,这会导致不同的停止偏移。

这是一个示例:

  path.p1 {
    fill: none;
    stroke-width: 20px;
  }
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

有没有一种方法可以使用一个渐变,但有一种聪明的方法可以通过 SVG 嵌套或 javascript 来引用它?

ccp*_*rog 5

使用gradientUnits="userSpaceOnUse". 这样,渐变以绝对单位定位,但始终在定义它的元素的局部坐标系中。

在您的情况下,将所有路径置于同一坐标系中意味着您定义了跨越所有路径的整体梯度。为避免这种情况,您必须更改它,例如通过定义transform属性。每条连续路径向右移动更多,而其在本地坐标系中测量的起点保持在同一位置。

  path.p1 {
    fill: none;
    stroke-width: 20px;
  }
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)