2017-04-11 109 views
1

我正在使用我的SVG创建动态路径。我现在想为我的路径添加渐变,但我被卡住了。我想的方式,如图2图像,而我需要它是那种在图像1.动态创建SVG路径内的渐变图层

Needed_Picture

目前我的梯度沿路径来

Current_Picture

我梯度和中风定义如下:

<defs> 
     <linearGradient id = "grad1" spreadMethod="reflect"> 
      <stop offset="0%" style="stop-color: lightcoral;" /> 
      <stop offset="50%" style="stop-color: #ffffff;" /> 
      <stop offset="100%" style="stop-color: lightcoral;" /> 
     </linearGradient> 
    </defs> 
</svg> 

脚本:

svgPath.setAttribute("stroke", "url(#grad1");` 
svgPath.setAttribute("fill", "none"); 
svgPath.setAttribute("stroke-linejoin", "round");` 
svgPath.setAttribute("stroke-width", "10"); 
}); 

回答

0

如果这就是你的意思,那么你不能沿着路径的行程渐变,在转角处等等。

相反,如果你只是想使它这样的梯度是垂直方向,那么你就需要使用xy1x2y2属性来设置线沿梯度运行。如果您不指定这些属性,则渐变将按照您的第二张图像水平取向。

<linearGradient id = "grad1" spreadMethod="reflect" x1="0" y1="0" x2="0" y2="1"> 
    <stop offset="0%" style="stop-color: lightcoral;" /> 
    <stop offset="50%" style="stop-color: #ffffff;" /> 
    <stop offset="100%" style="stop-color: lightcoral;" /> 
</linearGradient> 

如果希望有一个“管道”,像梯度效应,则该简单的方法是不同层的笔画宽度的多条路径。

下面是一个简单的例子来演示。

<svg fill="none"> 
 
    <polyline points="0,125, 150,125 150,25, 300,25" stroke="#666" stroke-width="30"/> 
 
    <polyline points="0,125, 150,125 150,25, 300,25" stroke="#999" stroke-width="24"/> 
 
    <polyline points="0,125, 150,125 150,25, 300,25" stroke="#ccc" stroke-width="16"/> 
 
    <polyline points="0,125, 150,125 150,25, 300,25" stroke="#eee" stroke-width="6"/> 
 
</svg>

+0

谢谢@保罗勒博。是的,的确,我想要一个类似管道的渐变效果,但不是使用多段线,而是想用一条路径来完成它。因为,它是在我的问题中动态使用鼠标创建的,所以我可以在其中创建图层的任何想法? –

+0

无论是路径还是折线都无所谓。所有层的坐标都是相同的。唯一的区别是行程厚度。这是假设你可以用一个路径描边来绘制你想要的管道。你需要比这更热门的管道形状吗? –

+0

不会。这样做可以,但是由于路径是通过鼠标的移动绘制的,我不知道如何将不同的笔画宽度合并到另一个中。 @PaulLeBeau –