简体   繁体   English

D3力图未按预期平移或缩放

[英]D3 force graph doesn't pan or zoom as expected

I've built a D3 force graph largely based on these really helpful examples . 我主要基于这些非常有用的示例构建了D3力图。

I wanted to add pan and zoom functionality, which I tried to do using another example (looks like I can only include two links, but Google "d3 force zoom eyaler" to find it). 我想添加平移和缩放功能,我尝试使用另一个示例来完成此操作(看起来我只能包含两个链接,但是Google可以通过“ d3强制缩放eyaler”找到它)。

Unfortunately, when I zoom out on a graph that is larger than the initial SVG, I get something like this: 不幸的是,当我缩小一个大于初始SVG的图形时,会得到如下信息:

Result of dragging and dropping 拖放的结果

Here's the relevant code: 以下是相关代码:

 var svg = d3.select("body").append("svg") .attr("width", width) .attr("height", height) .call(d3.behavior.zoom().scaleExtent([0.5,2]).on("zoom", redraw)); function redraw() { svg.attr("transform", "translate(" + d3.event.translate + ")" + " scale(" + d3.event.scale + ")"); } 

How can I change the pan and zoom behaviour so that it scrolls and makes it possible to see the rest of the graph, rather than just allowing me to move the square that was originally visible? 如何更改平移和缩放行为,以使其滚动并可以查看图形的其余部分,而不是仅允许我移动最初可见的正方形?

OK, looks like I worked it out... you need to perform the transform on a <g> rather than on the SVG itself. 好的,看起来我已经解决了...您需要在<g>而不是SVG本身上执行转换。 So: 所以:

 var svg = d3.select("body").append("svg") .attr("width", width) .attr("height", height) .call(d3.behavior.zoom().scaleExtent([0.5,2]).on("zoom", redraw)); var g = svg.append("g"); // add <g> function redraw() { g.attr("transform", // perform transform on g, not svg "translate(" + d3.event.translate + ")" + " scale(" + d3.event.scale + ")"); } 

Just putting this here in case anyone else made the same mistake! 只是把它放在这里,以防其他人犯同样的错误!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM