Quadtree layer to trigger the closest circle.
Last active
March 24, 2016 16:07
-
-
Save bricedev/4255cc933222d6efbacd to your computer and use it in GitHub Desktop.
Quadtree triggering
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<title>Quadtree</title> | |
<style> | |
.overlay { | |
fill: none; | |
pointer-events: all; | |
} | |
</style> | |
<body> | |
<script src="https://d3js.org/d3.v3.min.js"></script> | |
<script> | |
var width = 960, | |
height = 500; | |
var color = d3.scale.ordinal() | |
.range(["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69","#fccde5","#d9d9d9","#bc80bd","#ccebc5","#ffed6f"]); | |
var data = d3.range(150).map(function(d) { | |
return [d3.random.normal(width / 2, 80)(), d3.random.normal(height / 2, 80)()]; | |
}); | |
var quadtree = d3.geom.quadtree() | |
.extent([[-1, -1], [width + 1, height + 1]]) | |
(data); | |
var svg = d3.select("body").append("svg") | |
.attr("width", width) | |
.attr("height", height); | |
svg.selectAll(".node") | |
.data(nodes(quadtree)) | |
.enter().append("rect") | |
.attr("x", function(d) { return d.x0; }) | |
.attr("y", function(d) { return d.y0; }) | |
.attr("width", function(d) { return d.y1 - d.y0; }) | |
.attr("height", function(d) { return d.x1 - d.x0; }) | |
.style("fill","none") | |
.style("stroke","#ccc") | |
.style("shape-rendering","crispEdges"); | |
var point = svg.selectAll(".point") | |
.data(data) | |
.enter().append("circle") | |
.attr("cx", function(d) { return d[0]; }) | |
.attr("cy", function(d) { return d[1]; }) | |
.attr("r", 5) | |
.style("stroke-width",1) | |
.style("stroke","black") | |
.style("fill",function(d,i) { return color(i); }); | |
svg.append("rect") | |
.attr("class", "overlay") | |
.attr("width", width) | |
.attr("height", height) | |
.on("mousemove", mousemoved); | |
function mousemoved() { | |
point.style("stroke-width",1);; | |
point.filter(function(d) { return d === quadtree.find(d3.mouse(this)); }).style("stroke-width",3);; | |
} | |
function nodes(quadtree) { | |
var nodes = []; | |
quadtree.visit(function(node, x0, y0, x1, y1) { | |
node.x0 = x0, node.y0 = y0; | |
node.x1 = x1, node.y1 = y1; | |
nodes.push(node); | |
}); | |
return nodes; | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment