D3平移+缩放约束 [英] D3 pan+ zoom constraints

查看:312
本文介绍了D3平移+缩放约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在平移和缩放时将可变焦/拖动矩形从svg边界外部移出。我试图基于这个。


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

解决方案

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.

这篇关于D3平移+缩放约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆