Skip to content

Instantly share code, notes, and snippets.

@veltman
Last active July 3, 2016 05:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save veltman/b656785e18b8509993ef to your computer and use it in GitHub Desktop.
Save veltman/b656785e18b8509993ef to your computer and use it in GitHub Desktop.
Rainbow spiral

A spiraling Cubehelix rainbow from d3-scale.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
path {
fill: url(#rainbow);
stroke: #444;
stroke-width: 1px;
}
</style>
<body>
<script src="//d3js.org/d3.v4.0.0-alpha.18.min.js"></script>
<script>
var rainbow = d3.scaleRainbow(); // lazy
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.14/d3.min.js"></script>
<script>
var width = 960,
height = 500,
cx = width / 2,
cy = height / 2;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var gradient = svg.append("defs")
.append("radialGradient")
.attr("id","rainbow");
gradient
.selectAll("stop")
.data(d3.range(0,1,0.04))
.enter()
.append("stop")
.attr("offset",function(d){
return d;
})
.attr("stop-color",rainbow)
.each(rotateColor);
var spiral = svg.append("g")
.each(rotate);
spiral.append("path")
.attr("d",getSpiral());
function getSpiral() {
var inward = [],
outward = [];
var maxAngle = Math.PI * 2 * 12; // max turn (radians)
var distance = d3.scale.sqrt()
.domain([0,maxAngle])
.range([0.25,10]); // distance between turnings
var offset = d3.scale.linear()
.domain([0,maxAngle])
.range([0,36]); // width of spiral
d3.range(0,maxAngle,0.05).forEach(function(angle){
var a = distance(angle);
b = offset(angle);
inward.unshift([
cx + (a * angle - b) * Math.cos(angle),
cy + (a * angle - b) * Math.sin(angle)
]);
outward.push([
cx + (a * angle + b) * Math.cos(angle),
cy + (a * angle + b) * Math.sin(angle)
]);
});
return "M" + inward.join("L") + "L" + outward.join("L") + "Z";
}
function rotateColor() {
d3.select(this).transition()
.duration(4000)
.ease("linear")
.attrTween("stop-color",function(d){
return function(t) {
return rainbow((d + t) % 1);
};
})
.each("end",rotateColor);
}
function rotate() {
d3.select(this).transition()
.duration(4000)
.ease("linear")
.attrTween("transform",function(){
return function(t) {
return "rotate(" + (t * 360) + " " + cx + " " + cy + ")";
};
})
.each("end",rotate);
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment