我可以沿SVG路径应用渐变吗? [英] Can I apply a gradient along an SVG path?
问题描述
我想在我的网站上放置一个由脚本触发的简单加载指示器.它应该是一个简单的圆弧,该圆弧具有渐变并且在用户等待时正在旋转.我还没有尝试动画部分,但是暂时停留在静态样式上.这是到目前为止我得到的:
<svg version="1.1" baseProfile="full" xmlns="http://www.w3.org/2000/svg"
width="100" height="100">
<defs>
<linearGradient id="grad1">
<stop offset="0%" stop-color="red"/>
<stop offset="100%" stop-color="red" stop-opacity="0" />
</linearGradient>
</defs>
<path d="M50 10 A40 40 0 1 0 90 50"
stroke="url(#grad1)" stroke-width="10" fill="transparent"/>
</svg>
它从逆时针的顶部边缘向右边缘(270°)绘制圆弧,但是渐变是错误的.与其遵循路径以使起点(上边缘0°)不透明而终点(右边缘270°)透明,而是将弧形笔触的结果图像在屏幕空间中从左到右着色的方式,则是可以实现的.>
如何使渐变遵循弧形路径?
Mike Bostock提出了一种方法,尽管这并不容易: https://bl.ocks.org/mbostock/4163057
基本上,此技术使用 getPointAtLength
进行切片将笔划分为许多短笔划,为每个笔划指定插值的色标,然后对这些笔划之间的每个短笔划应用渐变.
如果您能应付挑战,祝您好运;)
编辑(2019年7月3日):
现在有了一个可以帮助您准确完成所需工作的库.不需要使用D3,但是您可以根据需要进行操作. 这是有关Medium的教程.
I'd like to put a simple loading indicator on my website that's triggered by a script. It should be a simple circle arc that's got a gradient and is spinning while the user is waiting. I haven't tried the animation part, but got stuck on the static styling for now. Here's what I've got so far:
<svg version="1.1" baseProfile="full" xmlns="http://www.w3.org/2000/svg"
width="100" height="100">
<defs>
<linearGradient id="grad1">
<stop offset="0%" stop-color="red"/>
<stop offset="100%" stop-color="red" stop-opacity="0" />
</linearGradient>
</defs>
<path d="M50 10 A40 40 0 1 0 90 50"
stroke="url(#grad1)" stroke-width="10" fill="transparent"/>
</svg>
It draws the arc, from the top edge anti-clockwise to the right edge (270°), but the gradient is wrong. Instead of following the path so that the beginning (top edge, 0°) is opaque and the end (right edge, 270°) is transparent, the resulting image of the arc stroke is coloured from left to right in screen space.
How can I make the gradient follow my arc path?
Mike Bostock figured out a way, though it's not easy: https://bl.ocks.org/mbostock/4163057
Basically, this technique uses getPointAtLength
to slice the stroke into many short strokes, specify interpolated color stops for each, and then apply a gradient to each short stroke between those stops.
Good luck if you're up to the challenge ;)
Edit (July 3rd, 2019):
There is now a library that will help you do exactly what you're looking for. It's not required to use D3, but you're able to if you desire. Here's a tutorial on Medium.
这篇关于我可以沿SVG路径应用渐变吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!