Reputation: 129
Hello Stackoverflowcommunity! I am having trouble getting d3 zoom working in my d3force-directed graph. I could achieve that it is zooming and panning but doing so breaks the alignment between the nodes and the links and i don't know how i could fix it.... I created a fiddle showing what i mean. https://jsfiddle.net/5jgrf5h8/5/
This is the code where i perform the zoom:
svg.call(d3.zoom()
//.scaleExtent([1 / 2, 4])
.on("zoom", zoomed))
.on("dblclick.zoom", null);
//.on("wheel.zoom", null);
function zoomed() {
//link.attr("transform", d3.event.transform);
link.attr("transform", "translate(" + d3.event.transform.x + "," + d3.event.transform.y + ") scale(" + d3.event.transform.k + ")");
node.style("transform", "translate(" + d3.event.transform.x + "px," + d3.event.transform.y + "px) scale(" + d3.event.transform.k + ")");
simulation.alphaTarget(0.001).restart();
simulation.alphaTarget(0);
}
Upvotes: 2
Views: 592
Reputation: 108512
When you apply the CSS scale
on your div
nodes, it's with an origin of 0,0
not with an origin of the position they are current in.
Try this:
function zoomed() {
// apply CSS scale with respect to current position
node.each(function(d){
var self = d3.select(this),
x = self.style("left"),
y = self.style("top");
self.style("transform-origin", "-" + x + " -" + y);
})
link.attr("transform", "translate(" + d3.event.transform.x + "," + d3.event.transform.y + ") scale(" + d3.event.transform.k + ")");
node.style("transform", "translate(" + d3.event.transform.x + "px," + d3.event.transform.y + "px) scale(" + d3.event.transform.k + ")");
simulation.alphaTarget(0.001).restart();
simulation.alphaTarget(0);
}
Updated fiddle here
Upvotes: 2