Skip to content

Instantly share code, notes, and snippets.

@michael
Forked from mbostock/.block
Created May 16, 2012 15:46
Show Gist options
  • Save michael/2711472 to your computer and use it in GitHub Desktop.
Save michael/2711472 to your computer and use it in GitHub Desktop.
click-to-center
<!DOCTYPE html>
<meta charset="utf-8">
<script src="http://mbostock.github.com/d3/d3.v2.js?2.8.1"></script>
<style>
.background {
fill: none;
pointer-events: all;
}
#states path {
fill: #aaa;
stroke: #fff;
stroke-width: 1.5px;
}
#states path:hover {
stroke: white;
}
</style>
<body>
<script>
var width = 960,
height = 500,
centered;
var projection = d3.geo.albersUsa()
.scale(width)
.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);
var states = svg.append("g")
.attr("id", "states");
states.append("rect")
.attr("class", "background")
.attr("width", width)
.attr("height", height)
.on("click", click);
d3.json("us-states.json", function(json) {
states.selectAll("path")
.data(json.features)
.enter().append("path")
.attr("d", path)
.on("click", click);
});
function click(d) {
// If the click was on the centered state or the background, re-center.
// Otherwise, center the clicked-on state.
if (!d || centered === d) {
projection.translate([width / 2, height / 2]);
centered = null;
} else {
var centroid = path.centroid(d),
translate = projection.translate();
projection.translate([
translate[0] - centroid[0] + width / 2,
translate[1] - centroid[1] + height / 2
]);
centered = d;
}
// Transition to the new projection.
states.selectAll("path").transition()
.duration(1000)
.attr("d", path);
}
</script>
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment