gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 20:42:18 24 4
gpt4 key购买 nike

我正在用 Javascript 创建不同的 L 形路径。它们的长度和位置不同。我想要一个 linearGradient 作为它们的笔触,其中第一个停止偏移位于 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 引用它?

最佳答案

使用 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>

关于javascript - 是否可以在某个绝对位置开始/停止 SVG 渐变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55131536/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com