Skip to content

Instantly share code, notes, and snippets.

@linssen
Last active June 6, 2023 17:49
Show Gist options
  • Save linssen/7352810 to your computer and use it in GitHub Desktop.
Save linssen/7352810 to your computer and use it in GitHub Desktop.
Programmatically and smoothly zoom to the centre.
<!DOCTYPE html>
<meta charset="utf-8">
<title>Zoom + Pan</title>
<script src="http://d3js.org/d3.v3.min.js"></script>
<style>
.overlay {
fill: none;
pointer-events: all;
}
button {
padding: 10px 20px;
}
</style>
<body>
<button id="zoom_in">+</button>
<button id="zoom_out">-</button>
<script>
var width = 960,
height = 500;
var randomX = d3.random.normal(width / 2, 80),
randomY = d3.random.normal(height / 2, 80);
var data = d3.range(2000).map(function() {
return [randomX(), randomY() ];
});
var zoom = d3.behavior.zoom().scaleExtent([1, 8]).on("zoom", zoomed);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.call(zoom)
.append("g");
svg.append("rect")
.attr("class", "overlay")
.attr("width", width)
.attr("height", height);
svg.selectAll("circle")
.data(data)
.enter().append("circle")
.attr("r", 2.5)
.attr("transform", function(d) { return "translate(" + d + ")"; });
function zoomed() {
svg.attr("transform",
"translate(" + zoom.translate() + ")" +
"scale(" + zoom.scale() + ")"
);
}
function interpolateZoom (translate, scale) {
var self = this;
return d3.transition().duration(350).tween("zoom", function () {
var iTranslate = d3.interpolate(zoom.translate(), translate),
iScale = d3.interpolate(zoom.scale(), scale);
return function (t) {
zoom
.scale(iScale(t))
.translate(iTranslate(t));
zoomed();
};
});
}
function zoomClick() {
var clicked = d3.event.target,
direction = 1,
factor = 0.2,
target_zoom = 1,
center = [width / 2, height / 2],
extent = zoom.scaleExtent(),
translate = zoom.translate(),
translate0 = [],
l = [],
view = {x: translate[0], y: translate[1], k: zoom.scale()};
d3.event.preventDefault();
direction = (this.id === 'zoom_in') ? 1 : -1;
target_zoom = zoom.scale() * (1 + factor * direction);
if (target_zoom < extent[0] || target_zoom > extent[1]) { return false; }
translate0 = [(center[0] - view.x) / view.k, (center[1] - view.y) / view.k];
view.k = target_zoom;
l = [translate0[0] * view.k + view.x, translate0[1] * view.k + view.y];
view.x += center[0] - l[0];
view.y += center[1] - l[1];
interpolateZoom([view.x, view.y], view.k);
}
d3.selectAll('button').on('click', zoomClick);
</script>
@jarandaf
Copy link

Thanks a lot for this, saved my day!

@kunwarj
Copy link

kunwarj commented Jun 6, 2023

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment