D3 pan+ zoom constraints

匿名 (未验证) 提交于 2019-12-03 02:29:01

问题:

I'm trying to zoomable/draggle rectangle from going outside of the svg bounds when panning and zooming. I've tried to implement it based off of this example, but i cant seem to get it to work. I've created this jsfiddle with just the rectangle that is zoomable and draggable. Again, im trying to make it so that you can not drag the rectangle outside of the svg box i put the border on. I know i need to update the move function. the code below is from the first link example but it does not seem to work well so i commented part of it out.

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 additionally i need to be able to drag the rectangle when you are zoomed in all the way and its bigger than the svg. In the image below, the blue rectangle is the svg and green would be the rectangle and you are zoomed in all the way so that the green rectangle takes up the much more than the SVG. This is similar to the map in the constrained zoom example. You can zoom into the states and drag across the country, navigating to states outside the current svg size

回答1:

You can do this by constraining the translation coordinates you set to the size of the box:

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 + ")"); 

This is constraining the x coordinate to be between 0 and the width minus however much space is required to show the box completely -- this depends on the zoom level and the term therefore contains s. For the y coordinate, it is exactly the same.

This is much easier if you don't use both a translation and explicit coordinate settings through x and y for the box -- to offset from the top left corner, simply set an initial translation.

Complete example here.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!