Limitations of panning and zooming D3

I am trying to scale / drag a rectangle from going beyond svg when panning and zooming. I tried to implement it based on this example , but I cannot get it to work. I created this jsfiddle with just a rectangle that can be scaled and dragged. Again, I am trying to make sure that you cannot drag the rectangle outside the svg window onto which I pasted the frame. I know that I need to update the move function. the code below is from the first link example, but it doesn't work well, so I commented on part of it.

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);
  svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}

Edit: so in addition I need to be able to drag the rectangle when you scale fully and more than svg. In the image below, the blue rectangle is svg, and the green will be a rectangle, and you will be scaled so that the green rectangle is much larger than the SVG. This is similar to the map in the limited zoom example . You can scale states and drag around the country, moving to states outside the current svg size

example

+1
source share
1 answer

You can do this by shifting the translation coordinates that you set to the field size:

var t = d3.event.translate,
    s = d3.event.scale;

t[0] = Math.max(0, Math.min(t[0], width - s*50));
t[1] = Math.max(0, Math.min(t[1], height - s*50));

svg.attr("transform", "translate(" + t + ")scale(" + d3.event.scale + ")");

x 0 , , - , s. y .

, , x y - , .

.

+6

Source: https://habr.com/ru/post/1648986/


All Articles