Can I apply a gradient along an SVG 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.


This type of gradient is not easy to achieve in SVG, see SVG angular gradient.

Also, transparent is not a valid color in SVG. You should state stop-opacity as in this example: http://jsfiddle.net/WF2CS/

I'm afraid the easiest solution might be a series of small arc paths with varying opacity.


path{
 fill : url(#gradient)
}
<svg width="660" height="220">
  <defs>
    <linearGradient id="gradient" x1="0%" y1="0%" x2="100%" y2="0%">
      <stop offset="0%"   stop-color="#05a"/>
      <stop offset="100%" stop-color="#0a5"/>
    </linearGradient>
  </defs>
 <path d="M150 0 L75 200 L225 200 Z" />
</svg>

I had this problem as well, so I created a library to assist in the creation of gradients that follow along a path. You can use it standalone in Javascript or alongside D3.js if you prefer. The library is 100% based off of Mike Bostock's work referenced in the first answer, but I've removed D3 as a required dependency.

I've also written a brief tutorial on Medium describing the backstory and usage..