Skip to content

Instantly share code, notes, and snippets.

@bwswedberg
Last active March 14, 2019 19:48
Show Gist options
  • Save bwswedberg/0a8f0351f8d04272e35f455290edf9a1 to your computer and use it in GitHub Desktop.
Save bwswedberg/0a8f0351f8d04272e35f455290edf9a1 to your computer and use it in GitHub Desktop.
Gradient Along Stroke (Naive) Spiral

This example demonstrates how to create a gradient that follows a stroke or path of a spiral. This method breaks the stroke into segments and uses stroke-linecap: round; to make the segments overlay and appear connected. The naive approach might useful if your stroke or path is relatively simple and you do not need a high level of precision.

Similarly, Gradient Along Stroke (Naive) shows how this method could be used in contrast to Mike Bostock's robust miter joint method demonstrated in Gradient Along Stroke.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
svg {
display: block;
width: 100%;
}
</style>
<svg></svg>
<script src="//d3js.org/d3.v4.min.js"></script>
<script>
var width = 960, height = 500;
var segments = d3.pairs(spiral([height * 0.1, height * 0.5], [0, Math.PI * 8], 0.0025));
var color = d3.scaleSequential(d3.interpolateRainbow)
.domain([0, segments.length - 1]);
d3.select('svg')
.attr('viewBox', '0 0 ' + width + ' ' + height)
.append('g')
.attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')scale(0.9)')
.selectAll('path')
.data(segments)
.enter().append('path')
.style('fill', 'none')
.style('stroke-width', 50)
.style('stroke-linecap', 'round')
.style('stroke', function(d, i) { return color(i); })
.attr('d', d3.line())
.style('stroke-opacity', 0)
.transition()
.delay(function(d,i) { return i * 5 + 500; })
.style('stroke-opacity', 1);
function spiral(radiusExtent, angleExtent, precision) {
var angle = d3.scaleLinear().range(angleExtent),
radius = d3.scaleLinear().range(radiusExtent);
return d3.range(0, 1, precision).concat(1)
.map(function(t) {
var a = angle(t), r = radius(t);
return [ r * Math.cos(a), r * Math.sin(a) ];
});
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment