动态在SVG路径中创建渐变层 [英] Creating a layer of gradient within an SVG path dynamically

查看:363
本文介绍了动态在SVG路径中创建渐变层的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用SVG创建动态路径.现在,我希望为路径添加渐变色,但是我被卡住了.我尝试的方式是,渐变是沿着图2所示的路径移动的,而我要求它是图1所示的那种.

I am creating a dynamic path using my SVG. I now wish to add gradient to my path but I am stuck. The way I am trying, my gradient is coming along the path as shown in image 2 while I require it to be the kind in image 1.

当前

我的渐变和笔触定义如下:

My gradient and stroke definitions are as follows :

    <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");
});

推荐答案

如果这就是您的意思,则不能沿着路径的笔触,在拐角处转弯等进行渐变.

You can't make a gradient run along the stroke of a path, turning at the corners etc., if that's what you mean.

如果相反,您只想使其渐变垂直放置,则需要使用xy1x2y2属性设置渐变沿其运行的线.如果您未指定这些属性,则渐变将根据您的第二张图片水平放置.

If instead you just want to make it so the gradient is oriented vertically, then you need to use the x, y1, x2 and y2 attributes to set the line along which the gradient runs. If you don't specify these attributes, the gradient is oriented horizontally as per your second image.

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

如果要具有类似管道"的渐变效果,则最简单的方法是对具有不同笔触宽度的多个路径进行分层.

If you want to have a "pipe" like gradient effect, then the simplest method is to layer multiple paths of different stroke widths.

这是一个简单的示例来演示.

Here's a simple example to demonstrate.

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

这篇关于动态在SVG路径中创建渐变层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆