score:36

Accepted answer

Change this:

.call(d3.zoom().on("zoom", function () {
    svg.attr("transform", "translate(" + d3.event.translate 
    + ")" + " scale(" + d3.event.scale + ")")
}))

To this:

.call(d3.zoom().on("zoom", function () {
        svg.attr("transform", d3.event.transform)
}))

Here is the fiddle: https://jsfiddle.net/gerardofurtado/c8bga82b/

score:6

The accepted answer is great !

For those of you who want to restrict the pan & zoom in boundaries (like here)..

Change this:

// width, height = viewport width, height
.call(d3.zoom().on("zoom", function () {
  var tx = Math.min(0, Math.max(d3.event.translate[0], width - width * d3.event.scale));
  var ty = Math.min(0, Math.max(d3.event.translate[1], height - height * d3.event.scale));
  svg.attr("transform", "translate(" + [tx, ty] + ") scale(" + d3.event.scale + ")");
});

To this:

.call(d3.zoom().on("zoom", function () {
  d3.event.transform.x = Math.min(0, Math.max(d3.event.transform.x, width - width * d3.event.transform.k));
  d3.event.transform.y = Math.min(0, Math.max(d3.event.transform.y, height - height * d3.event.transform.k));
  svg.attr("transform", d3.event.transform);
}));

score:9

I can't reply to your comment to the answer, but here is how to zoom only the x-axis:

svg.attr(
    "transform",
    'translate('+d3.event.transform.x+',0) scale('+d3.event.transform.k+',1)'
)}))

Updated jsFiddle: https://jsfiddle.net/axge6a04/1/


Related Query