我正在从一个节点开始一个图形项目。当我将其拖动到某处时,我希望它可以平滑地返回到svg的中心,但相反,它会毛刺回到中心。
var simulation = d3.forceSimulation()
.force("center", d3.forceCenter(svgWidth/2, svgHeight/2));
我认为我可能没有正确配置forceCenter(),或者因为没有其他节点,所以没有其他主体可以与之交互,所以这就是D3的工作方式。
答案 0 :(得分:5)
...也许因为没有其他节点,所以没有其他物体可以与之交互,所以这就是D3的工作方式。
是的,您的直觉在这里是(部分)正确的,这种力模拟没有错。我认为这里的问题来自对forceCenter
的目的的误解:forceCenter
不能使节点平稳地到达指定位置(以下更多内容)。实际上,如果在该模拟中有另一个节点,则可以看到,通过拖动一个节点,另一个节点也将移动,因此质心保持在同一位置。
话虽如此,如果您使用forceCenter
和{{1来代替forceX
,而不是forceY
,则可以看到它按预期工作,也就是说,节点平滑地回到了中心。 }} ...
var simulation = d3.forceSimulation()
.force("x", d3.forceX(svgWidth / 2))
.force("y", d3.forceY(svgHeight / 2));
...而不更改任何alpha
,alphaTarget
,velocityDecay
等...
这是仅有更改的代码:
////////////////////////////////////////////////////
// SVG setup
////////////////////////////////////////////////////
var svgWidth = 400,
svgHeight = 400;
var svgRef = d3.select("body").append("svg")
.attr("width",svgWidth)
.attr("height",svgHeight);
svgRef.append("rect")
.attr("width", svgWidth)
.attr("height", svgHeight);
////////////////////////////////////////////////////
// Data
////////////////////////////////////////////////////
var nodes_data = [{id: "0"}];
var links_data = [];
////////////////////////////////////////////////////
// Links and nodes setup
////////////////////////////////////////////////////
var linksRef = svgRef.selectAll(".link")
.data(links_data).enter()
.append("line")
.attr("class", "link");
var nodesRef = svgRef
.selectAll(".node")
.data(nodes_data).enter()
.append("g").attr("class", "node")
.append("circle")
.attr("r", 10)
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
////////////////////////////////////////////////////
// Simulation setup
////////////////////////////////////////////////////
var simulation = d3.forceSimulation()
.force("x", d3.forceX(svgWidth / 2))
.force("y", d3.forceY(svgHeight / 2));
simulation.nodes(nodes_data).on("tick", ticked);
simulation.force("link").links(links_data);
function ticked() {
nodesRef.attr("transform", function (d) {return "translate(" + d.x + "," + d.y + ")";})
linksRef.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; });
}
////////////////////////////////////////////////////
// Dragging
////////////////////////////////////////////////////
function dragstarted (d) {
if (!d3.event.active) simulation.alphaTarget(1).restart();
d.fx = d.x;
d.fy = d.y;
}
function dragged (d) {
d.fx = d3.event.x;
d.fy = d3.event.y;
}
function dragended (d) {
if (!d3.event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
.link {
stroke: #000;
stroke-width: 2px;
}
.node {
fill: #CCC;
stroke: #000;
stroke-width: 1px;
}
rect {
fill: none;
stroke: #000;
stroke-width: 2px;
pointer-events: all;
}
<script src="https://d3js.org/d3.v5.min.js"></script>