d3 js v4 + 缩放限制中的地图缩放和平移 [英] Map zoom and pan in d3 js v4 + scale limit

查看:68
本文介绍了d3 js v4 + 缩放限制中的地图缩放和平移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. 我有 这个 d3 js 地图.我试图做一个像缩放这样简单的事情和锅,只是停滞不前.现在只有点缩放(我使用 v4).如何同步"点的缩放和平移以及地图 svg?

  1. I've got this d3 js map. I've tried to make such a simple thing as zoom and pan and just stalled. Now only dots zooms (I use v4). How to 'synchronize' zoom and pan of dots and map svg?

如何在 d3 v4 中设置缩放和平移的限制?我希望它像 this

How to set limits of zoom and pan in d3 v4? I want it to be like this

var svg = d3.select("body")
          .append("svg")
          .attr("width", width)
          .attr("height", height)
          .style("border","none") 
          .style("background-color", "none")
          .call(d3.zoom().on("zoom", function () {
          svg.attr("transform", d3.event.transform)
                 }))
          .append("g");

推荐答案

圆圈会缩放,但路径不会缩放,因为您附加它们的方式.首先,让我们看看如何应用缩放:

The circles scale but the paths do not because of how you append them. First, let's see how you apply the zoom:

var svg = d3.select("body")
      .append("svg")
      ...
      .call(d3.zoom().on("zoom", function () {
      svg.attr("transform", d3.event.transform)
             }))
      .append("g");  // returns a selection of a newly appended g element

所以选择 svg 实际上是一个 g 元素.在 svg 元素(不是 svg 选择)上调用缩放时,它会修改 svg 选择(实际上包含一个 g):svg.attr(("transform"....

So the selection svg is actually a g element. While zoom is called on the svg element (not svg selection) it modifies the svg selection (which is actually holds a g): svg.attr(("transform"....

当你附加你的路径时,你使用 var map = d3.select("svg").insert(... 并创建一个新的 g 来保存路径. 但是 - 这个 g 不在选择 svg 中或它的子节点 - 所以它没有更新:d3.select("svg") != svg 在这种情况下.相反,使用:

When you append your paths you use var map = d3.select("svg").insert(... and create a new g to hold the paths. But - this g is not in or a child of the selection svg - so it is not updated: d3.select("svg") != svg in this case. Instead, use:

 var map = svg.insert(...  // we insert into the svg selection which holds a g

通过这种方式,我们将元素插入到每次缩放都会更新的父 g 中.

This way we are inserting elements into the parent g that is updated each zoom.

虽然这确实是第二个问题,但解决方案很简单.d3.zoom() 行为可以同时受到缩放和平移的约束:

While this really is a second question, the solution is simple enough. A d3.zoom() behavior can be constrained by both scale and translate:

d3.zoom().scaleExtent([1,4]) // limit scale to full size or 4x size.
   .translateExtent([[0,0],[width,height]])  // limit pan to original SVG dimensions

zoom.translateExtent([p1,p2]) 取两个点,左上角和右下角.如果您的特征在最初以 1 的比例加载时没有超出 SVG 边界,我们可以基于这些维度进行约束.

zoom.translateExtent([p1,p2]) takes two points, upper left and lower right. We can constrain based on these dimensions if your features don't extend past the SVG bounds when initially loaded with a scale of 1.

这是更新的bin.

这篇关于d3 js v4 + 缩放限制中的地图缩放和平移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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