Skip to content

Instantly share code, notes, and snippets.

@hugozap
Created January 8, 2018 17:19
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 hugozap/a9a603d79070209411d9bbf7e616e7d0 to your computer and use it in GitHub Desktop.
Save hugozap/a9a603d79070209411d9bbf7e616e7d0 to your computer and use it in GitHub Desktop.
butterfly2
<!-- Adapted from the voronoi example found here: https://bl.ocks.org/mbostock/4060366 -->
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.links {
}
.polygons {
fill: none;
stroke: none;
}
.polygons :first-child {
fill: lightblue;
}
.sites {
fill: #000;
stroke: #fff;
}
.sites :first-child {
fill: #fff;
}
</style>
<svg width="960" height="500"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-ease.v1.min.js"></script>
<script>
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height"),
target = [0,0]
var sites = d3.range(100)
.map(function(d) { return [Math.random() * width, Math.random() * height]; });
var voronoi = d3.voronoi()
.extent([[-1, -1], [width + 1, height + 1]]);
var polygon = svg.append("g")
.attr("class", "polygons")
.selectAll("path")
.data(voronoi.polygons(sites))
.enter().append("path")
.call(redrawPolygon);
var link = svg.append("g")
.attr("class", "links")
.selectAll("line")
.data(voronoi.links(sites))
.enter().append("line")
.call(redrawLink);
function newTarget() {
target = [Math.random() * width, Math.random() * height];
}
var customElastic = d3.easeElastic.period(0.4);
var start = null;
function step(timestamp) {
var stepSize = 20;
var difX = Math.abs(sites[0][0] - target[0])
var difY = Math.abs(sites[0][1] - target[0])
difX > 10 && (sites[0][0] += stepSize * (sites[0][0] < target[0] ? 1 : -1))
difY > 10 && (sites[0][1] += stepSize * (sites[0][1] < target[1] ? 1 : -1))
if (difX < 10 || difY < 10) {
newTarget();
}
redraw()
console.log(sites[0])
window.requestAnimationFrame(step);
}
window.requestAnimationFrame(step);
function redraw() {
var diagram = voronoi(sites);
polygon = polygon.data(diagram.polygons()).call(redrawPolygon);
link = link.data(diagram.links()), link.exit().remove();
link = link.enter().append("line").merge(link).call(redrawLink);
}
function redrawPolygon(polygon) {
polygon
.attr("d", function(d) { return d ? "M" + d.join("L") + "Z" : null; });
}
function redrawLink(link) {
link
.attr("x1", function(d) { return d.source[0]; })
.attr("y1", function(d) { return d.source[1]; })
.attr("x2", function(d) { return d.target[0]; })
.attr("y2", function(d) { return d.target[1]; });
}
function redrawSite(site) {
site
.attr("cx", function(d) { return d[0]; })
.attr("cy", function(d) { return d[1]; });
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment