简体   繁体   中英

D3 force graph doesn't pan or zoom as expected

I've built a D3 force graph largely based on these really helpful examples .

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).

Unfortunately, when I zoom out on a graph that is larger than the initial SVG, I get something like this:

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. 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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