zeleniy
zeleniy

Reputation: 2272

d3.js v4 programmatic Pan+Zoom. How?

I did a small example of what i am trying to implement, here it is - https://jsfiddle.net/zeleniy/4sgqgcx0/. You can zoom and pan SVG image as usual. But i have no idea how to implement zoom programmatically when user click on "+" and "-" buttons. Especially if he already zoom in/out and pan original image. Could you help me?

On line 13 of the code you will find zoom event handler.

var zoom = d3.zoom()
    .on('zoom', function() {
        canvas.attr('transform', d3.event.transform);
    });

On lines 35 and 39 - zoom event handlers

d3.select('#zoom-in').on('click', function() {
    // what here?
});

d3.select('#zoom-out').on('click', function() {
    // what here?
});

So when user click on "+" app should zoom in as if mouse were at the center of SVG element. And the same with "-".

Upvotes: 6

Views: 3542

Answers (1)

zeleniy
zeleniy

Reputation: 2272

Thanks to Fil. Here is an updated version of jsfiddle.

d3.select('#zoom-in').on('click', function() {
  // Smooth zooming
  zoom.scaleBy(svg.transition().duration(750), 1.3);
});

d3.select('#zoom-out').on('click', function() {
  // Ordinal zooming
  zoom.scaleBy(svg, 1 / 1.3);
});

Upvotes: 6

Related Questions