Skip to content

Instantly share code, notes, and snippets.

@trinary
Last active September 15, 2016 23:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trinary/051e215882ac16bfb0f442ea33d90798 to your computer and use it in GitHub Desktop.
Save trinary/051e215882ac16bfb0f442ea33d90798 to your computer and use it in GitHub Desktop.
spirals!
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
.spiral {
fill: none;
stroke: #ccc;
stroke-width: 2px;
}
</style>
</head>
<body>
<script>
let scale = d3.scaleLinear().domain([0,400]).range([0,1]);
let svg = d3.select("body")
.append("svg")
.attr("width", 960)
.attr("height", 500);
let center = svg.append("g")
.attr("transform", "translate(540, 250)");
let spiralify = function(elem, curve, color, i) {
if (i >= Math.abs(360 / curve)) { return;}
let current = elem.select("rect");
let next = elem.append("g")
.attr("transform", "rotate(" + curve + ")");
next.append("rect")
.classed("spiral", true)
.attr("x", current.attr("x"))
.attr("y", current.attr("y"))
.attr("width", current.attr("width"))
.attr("height", current.attr("height"))
.style("stroke", color);
spiralify(next, curve, color, i + 1);
}
let dragStart = function(d) {
let container = center.append("g")
.classed("container", true)
let diagDistance = Math.sqrt(Math.pow(d3.event.x - 540, 2) + Math.pow(d3.event.y - 250, 2));
let color = d3.interpolateCool(scale(diagDistance));
let rect = container.append("rect")
.classed("spiral", true)
.classed("dragging", true)
.attr("x", d3.event.x - 540)
.attr("y", d3.event.y - 250)
.attr("width", 0)
.attr("height", 0)
.style("stroke", color);
};
let dragMove = function(d) {
let diagDistance = Math.sqrt(Math.pow(d3.event.x - 540, 2) + Math.pow(d3.event.y - 250, 2));
let color = d3.interpolateCool(scale(diagDistance));
let rect = center.select(".dragging");
rect
.attr("width", d3.event.x - d3.event.subject.x)
.attr("height", d3.event.y - d3.event.subject.y)
.style("stroke", color);
};
let dragEnd = function(d) {
let diagDistance = Math.sqrt(Math.pow(d3.event.x - 540, 2) + Math.pow(d3.event.y - 250, 2));
let color = d3.interpolateCool(scale(diagDistance));
let rect = center.select(".dragging");
let container = d3.select(rect.node().parentNode);
spiralify(container, Math.random() * -20, color, 0);
center.selectAll(".dragging").classed("dragging", false);
}
let drag = d3.drag()
.on("start", dragStart)
.on("drag", dragMove)
.on("end", dragEnd);
svg.call(drag);
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment