0

I am trying to limit pan in d3 zoom but I am not getting correct results. I am using following code to extent both scale and translate.

var treeGroup = d3.select('.treeGroup');
var rootSVG = d3.select('.rootSVG')
var zoom = d3.zoom()
     .scaleExtent([1.6285, 3])
     .translateExtent([[0, 0],[800, 600]])
     .on('zoom', function(){
           treeGroup.attr('transform', d3.event.transform);
     })

rootSVG.call(zoom);

Here is the JSFiddle: https://jsfiddle.net/nohe76yd/45/

scaleExtent works fine but translateExtent is giving issues. How do I specify correct value for translateExtent so that while panning content always stays inside the svg container?

Bhavesh Jadav
  • 695
  • 1
  • 13
  • 33
  • 1
    the translate extent depends on the zoom/scale factor. In the on-zoom function modify the transform by using Math.min and Math.max. https://stackoverflow.com/a/51563890/9938317 – rioV8 Aug 08 '18 at 08:59

1 Answers1

1

The translateExtent works best when used dynamically to the graph group you're using. It takes two arguments: topLeft and bottomRight, which are x and y coordinates each.

In my example, I recalculate the extent based on the graph's size, with the help of getBBox() and adding some margins. Take a look, it might help you: https://bl.ocks.org/agnjunio/fd86583e176ecd94d37f3d2de3a56814

EDIT: Adding the code that does this to make easier to read, inside zoom function.

// Define some world boundaries based on the graph total size
// so we don't scroll indefinitely
const graphBox = this.selections.graph.node().getBBox();
const margin = 200;
const worldTopLeft = [graphBox.x - margin, graphBox.y - margin];
const worldBottomRight = [
    graphBox.x + graphBox.width + margin,
    graphBox.y + graphBox.height + margin
];
this.zoom.translateExtent([worldTopLeft, worldBottomRight]);
ilim
  • 4,477
  • 7
  • 27
  • 46
  • I am tying to do this, to avoid infinite panning to left (x-axis) but .getBBox() is returning all zero values. x,y, width and height. could you please help on this – Meeran0823 Feb 12 '21 at 13:26