Gradient Along Stroke
This example shows a curved SVG path rendered as a continuous rainbow gradient that follows the stroke, with colors interpolated from green to red along the path’s length. The technique samples points along the path using the SVG `getPointAtLength` method, then computes miter joints via line-line intersection to fill each segment with a solid color from `d3.interpolateRainbow`. A thin stroke is added to each segment to avoid antialiasing artifacts. The code uses D3 v4 and renders entirely in SVG.
AI-generated descriptionThis example demonstrates how to create a gradient that follows a stroke. This technique is sometimes used to indicate directionality along a curved edge, such as with hierarchical edge bundling.
To start, take any SVG path element and uniformly sample points along the path using getPointAtLength. (This method can also be used for path tweening.) Then, for each segment between adjacent points, compute the miter joint via line-line intersection. Lastly fill each segment by interpolating the start and end colors, here green to red, using the normalized length t along the path. Although each segment is a constant color, there are many segments to give the appearance of a continuous gradient.
This example uses a thin stroke in addition to filling the segments. This avoids antialiasing artifacts due to most web browsers not implementing full-scene antialiasing.