我正在尝试将zoom suport添加到D3 https://www.d3-graph-gallery.com/graph/network_basic.html的基本网络示例中。
到目前为止,这与
配合得很好svg = svg.append("svg")
.call(d3.zoom().on("zoom",function () {
svg.attr("transform",d3.event.transform)
}))
.append("g")
但是,缩放事件仅在将鼠标直接放置在行或节点上时触发。我也想触发背景缩放,但是还没有弄清楚如何做到这一点。 我怀疑可能存在直接启用此行为的开关(再次,找不到它)。另外,我考虑过在网络图的背景中放置一个矩形来伪造“背景zpooming”。 只要指定了节点的固定位置,此方法就很好用,但是在应用强制算法后,矩形将需要适应网络的更新坐标,而我也无法确定这一点。 任何帮助表示赞赏!
作为参考,这是脚本(包括缩放)
svg = svg.append("svg")
.call(d3.zoom().on("zoom",d3.event.transform)
}))
.append("g")
var link = svg
.selectAll("line")
.data(data.links)
.enter()
.append("line")
.style("stroke","#aaa")
// Initialize the nodes
var node = svg
.selectAll("circle")
.data(data.nodes)
.enter()
.append("circle")
.attr("r",20)
.style("fill","#69b3a2")
// Let's list the force we wanna apply on the network
var simulation = d3.forceSimulation(data.nodes) // Force algorithm is applied to data.nodes
.force("link",d3.forceLink() // This force provides links between nodes
.id(function(d) { return d.id; }) // This provide the id of a node
.links(data.links) // and this the list of links
)
.force("charge",d3.forceManyBody().strength(-400)) // This adds repulsion between nodes. Play with the -400 for the repulsion strength
.force("center",d3.forceCenter(width / 2,height / 2)) // This force attracts nodes to the center of the svg area
.on("end",ticked);
// This function is run at each iteration of the force algorithm,updating the nodes position.
function ticked() {
link
.attr("x1",function(d) { return d.source.x; })
.attr("y1",function(d) { return d.source.y; })
.attr("x2",function(d) { return d.target.x; })
.attr("y2",function(d) { return d.target.y; });
node
.attr("cx",function (d) { return d.x+6; })
.attr("cy",function(d) { return d.y-6; });
}