Last active
December 13, 2015 20:48
-
-
Save oeon/4972507 to your computer and use it in GitHub Desktop.
click a d3 polygon, test
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"> | |
<style> | |
rect { | |
fill: none; | |
pointer-events: all; | |
} | |
.feature { | |
fill: #ccc; | |
opacity: .5; | |
cursor: pointer; | |
} | |
.feature.active { | |
fill: orange; | |
} | |
.mesh { | |
fill: none; | |
stroke: black; | |
stroke-width: .3px; | |
stroke-linejoin: bevel; | |
} | |
</style> | |
<body> | |
<script src="http://d3js.org/d3.v3.min.js"></script> | |
<script src="http://d3js.org/topojson.v0.min.js"></script> | |
<script> | |
var width = 960, | |
height = 500, | |
active; | |
var projection = d3.geo.mercator() | |
.scale(180000) | |
.center([-119.5, 35]) | |
.translate([width / 2, height / 2]); | |
var path = d3.geo.path() | |
.projection(projection); | |
var svg = d3.select("body").append("svg") | |
.attr("width", width) | |
.attr("height", height); | |
svg.append("rect") | |
.attr("width", width) | |
.attr("height", height) | |
.on("click", reset); | |
var g = svg.append("g"); | |
d3.json("h2o.json", function(error, h2o) { | |
g.selectAll("path") | |
.data(topojson.object(h2o, h2o.objects.hu12).geometries) | |
.enter().append("path") | |
.attr("d", path) | |
.attr("class", "feature") | |
.on("click", click); | |
g.append("path") | |
.datum(topojson.mesh(h2o, h2o.objects.hu12, function(a, b) { return a !== b; })) | |
.attr("class", "mesh") | |
.attr("d", path); | |
}); | |
function click(d) { | |
if (active === d) return reset(); | |
g.selectAll(".active").classed("active", false); | |
d3.select(this).classed("active", active = d); | |
var b = path.bounds(d); | |
g.transition().duration(750).attr("transform", | |
"translate(" + projection.translate() + ")" | |
+ "scale(" + .95 / Math.max((b[1][0] - b[0][0]) / width, (b[1][1] - b[0][1]) / height) + ")" | |
+ "translate(" + -(b[1][0] + b[0][0]) / 2 + "," + -(b[1][1] + b[0][1]) / 2 + ")"); | |
} | |
function reset() { | |
g.selectAll(".active").classed("active", active = false); | |
g.transition().duration(750).attr("transform", ""); | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment