Force.drag().on返回未定义的值

Force.drag().on returns undefined

本文关键字:未定义 返回 on drag Force      更新时间:2023-09-26

Im使用粘性力布局:http://bl.ocks.org/mbostock/3750558

我试图在我的布局中实现粘性拖动。所以我有这样的东西:

    force = d3.layout.force()
        .charge(-120)
        .linkDistance(30)
        .size([width, height])
        .on("tick", tick);;
        var nodeDrag = force.drag()
        .on("dragstart", dragstart);
//then for drag i call nodeDrag on the node after I append circle :
.call(nodeDrag)

function dragstart(d) {
  d3.select(this).classed("fixed", d.fixed = true);
}

这将返回错误:TypeError: Cannot read property 'on' of undefined

线上的哪个点:var nodeDrag = force.drag()

如果我使用d3.behavior.drag(),它会加载可视化,但我不能拖动,因为我猜它没有使用我的force布局。

有什么想法吗?

我自己设法解决了这个问题。基本上,我必须自己计算运动,这就是为什么没有一个节点工作的原因。所以我是这样实现的:

var nodeDrag = d3.behavior.drag()
    .on("dragstart", dragstart) //-when you first click
    .on("drag", dragmove) //-when you're dragging
    .on("dragend", dragend); //-when the drag has ended
function dragstart(d, i) //-ability to move nodes to one place and keep them there
{
    force.stop(); //-stop the force layout as soon as you move nodes
}
function dragmove(d, i) //-updates the co-ordinates 
{
    //d.px += d3.event.dx;
    //d.py += d3.event.dy;
    d.x += d3.event.dx;
    d.y += d3.event.dy; 

    d3.select(this).attr("transform", function(d,i)
    {
        return "translate(" + [ d.x,d.y ] + ")";
    });
    tick(); //-updates positions
}
function dragend(d, i) //-when you stop dragging the node
{
    d.fixed = true; //-D3 giving the node a fixed attribute
    tick(); //-update positions
}

节点没有移动的主要原因是我没有告诉它们移动。此外,调用tick会更新所有其他节点的位置。希望这能帮助遇到同样问题的人:)