2014-11-15 24 views
1

我的最終目標是獲得類似於this的東西。因此我使用d3js,但我是一個非常初學者。我嘗試了很多與力佈局,但我認爲我不需要任何動畫,只有我可以拖動更新鏈接的節點。我已經定義了一個拖拽行爲的工作原理:D3js拖動節點和鏈接的行爲

var dragListener = d3.behavior.drag() 
    .on("dragstart", function (d) { 
     dragStarted = true; 
     d3.event.sourceEvent.stopPropagation(); 
    }) 
    .on("drag", function (d) { 
     // update the node position 
     var n = d3.select(this); 
     n.attr("cx", d.x = d3.event.x); 
     n.attr("cy", d.y = d3.event.y); 
     update(); 
    }) 
    .on("dragend", function (d) {}); 

我的更新方法是:

function update() { 
    force.nodes(nodes) 
     .links(links); 

    // Update links 
    var l = vis.select("#linkG").selectAll("line.link") 
       .data(links, function (d) { return d.source.id + "-" + d.target.id; }) 
       .enter() 
       .append("svg:line") 
       .attr("class", "link"); 

    l.style("stroke", "#000") 
    .style("stroke-width", 1); 

    // Update nodes 
    var n = vis.select("#nodeG").selectAll("a") 
       .data (nodes, function (d) { return d.id; }) 
       .enter() 
       .append("svg:a").attr("xlink:href", function (d) { return "/user/" + d.id; }) 
       .append("svg:circle") 
       .attr("class", "node") 
       .attr("r", function (d) { return d.r; }) 
       .style("fill", "#454545") 
       .style("stroke", "#e7ecef") 
       .style("stroke-width", 3) 
       .call(dragListener); 

    force.on("tick", function() { 
     nodes[0].x = WIDTH/2; 
     nodes[0].y = HEIGHT/2; 

     // Tried to update the link positions 
     l.attr("x1", function (d) { console.log(d); return d.source.x; }) // HERE 
     .attr("y1", function (d) { return d.source.y; }) 
     .attr("x2", function (d) { return d.target.x; }) 
     .attr("y2", function (d) { return d.target.y; }); 

     // Hopefully updates the node positions 
     n.attr("cx", function (d) { console.log(d.x); return d.x; }) 
     .attr("cy", function (d) { return d.y; }); 
    }); 
} 

我已經在初始化啓動力佈局。聲明console.log(d)從不觸發。數據都很好,在html中所有的元素都創建好了。

enter image description here

的問題是,該鏈接不顯示或更新。有人可以幫助我獲得正確的行爲嗎?

+0

對初學者來說非常有抱負! :) – Pogrindis

+0

好吧,我幾乎整個3天嘗試它。 – Chryb

+0

我把我的帽子給你!你是否能夠在console.log之後的'return d.x;'上放置一個斷點? – Pogrindis

回答

0

最後我有解決方案(希望)。一個很好的幫助是這些堆棧溢出post。現在我可以正確拖拽節點了。關鍵是力量佈局的d.fixed = true。也許這有助於他人。