[英]Drag, drop and fix a node in D3JS
從此示例中: http : //bl.ocks.org/mbostock/3750558
您需要添加一個拖動函數的調用:
var drag = force.drag()
.on("dragstart", dragstart);
如下:
function dragstart(d) {
d3.select(this).classed("fixed", d.fixed = true);
}
關鍵是將d.fixed
設置為true
。
編輯
在您的小提琴中,您沒有調用node_drag。 因此,您需要像這樣在節點上調用它:
var node = gnodes.append("circle")
.attr("class", "node")
.attr("r", 5)
.style("fill", function(d) {
thelistofcolors[d.group] = color(d.group);
return color(d.group); })
.call(node_drag); // <<<<<<<this line
然后將對號更改為一個函數,以便以后可以調用它:
force.on("tick", tick);
function tick() {
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; });
gnodes.attr("transform", function(d) {
return 'translate(' + [d.x, d.y] + ')';
});
};
更新了小提琴,其中顯示了所有數據(點擊時未過濾): https : //jsfiddle.net/vgy1s8k3/4/
解決方案是在dragstart上將“固定”節點屬性設置為true,這將允許追加位置。
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="//d3js.org/d3.v3.min.js"></script>
<style>
.node {
stroke: #fff;
stroke-width: 1.5px;
}
.link {
stroke: #999;
stroke-opacity: .6;
}
</style>
</head>
<body>
<script>
var width = 1280,
height = 960;
var color = d3.scale.category20();
var force = d3.layout.force()
.charge(-120)
.linkDistance(30)
.size([width, height]);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
d3.json("graph.json", function(error, graph) {
if (error) throw error;
force
.nodes(graph.nodes)
.links(graph.links)
.start();
var link = svg.selectAll("graph.link")
.data(graph.links)
.enter().append("line")
.attr("class", "link")
.style("stroke-width", function(d) { return Math.sqrt(d.value); });
var node = svg.selectAll("graph.node")
.data(graph.nodes)
.enter().append("circle")
.attr("class", "node")
.attr("r", 5)
.style("fill", function(d) { return color(d.fill); })
.call(force.drag);
var drag = force.drag()
.on("dragstart", dragstart);
function dragstart(d) {
d.fixed = true;
}
node.append("title")
.text(function(d) { return d.name });
force.on("tick", tick);
function tick() {
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("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
};
});
</script>
</body>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.