Skip to content

Instantly share code, notes, and snippets.

@mbostock
Last active April 6, 2020 10:58
Show Gist options
  • Save mbostock/4987520 to your computer and use it in GitHub Desktop.
Save mbostock/4987520 to your computer and use it in GitHub Desktop.
Constrained Zoom
license: gpl-3.0

This example demonstrates using the zoom event to constrain the zoom behavior’s translation. This implementation is a bit heavy-handed, as the translate constraint is zoom-dependent.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
.overlay {
fill: none;
pointer-events: all;
}
.land {
fill: #000;
}
.boundary {
fill: none;
stroke: #fff;
stroke-linejoin: round;
stroke-linecap: round;
}
</style>
<script src="//d3js.org/d3.v3.min.js"></script>
<script src="//d3js.org/topojson.v1.min.js"></script>
<body>
<script>
var width = 960,
height = 500;
var projection = d3.geo.mercator()
.translate([0, 0])
.scale(width / 2 / Math.PI);
var zoom = d3.behavior.zoom()
.scaleExtent([1, 8])
.on("zoom", move);
var path = d3.geo.path()
.projection(projection);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")
.call(zoom);
var g = svg.append("g");
svg.append("rect")
.attr("class", "overlay")
.attr("x", -width / 2)
.attr("y", -height / 2)
.attr("width", width)
.attr("height", height);
d3.json("/mbostock/raw/4090846/world-50m.json", function(error, world) {
if (error) throw error;
g.append("path")
.datum(topojson.feature(world, world.objects.countries))
.attr("class", "land")
.attr("d", path);
g.append("path")
.datum(topojson.mesh(world, world.objects.countries, function(a, b) { return a !== b; }))
.attr("class", "boundary")
.attr("d", path);
});
function move() {
var t = d3.event.translate,
s = d3.event.scale;
t[0] = Math.min(width / 2 * (s - 1), Math.max(width / 2 * (1 - s), t[0]));
t[1] = Math.min(height / 2 * (s - 1) + 230 * s, Math.max(height / 2 * (1 - s) - 230 * s, t[1]));
zoom.translate(t);
g.style("stroke-width", 1 / s).attr("transform", "translate(" + t + ")scale(" + s + ")");
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment