使用Javascript连接SVG圈子
问题描述:
我想通过在源圆圈和目标矩形之间画线来连接SVG圆圈和矩形。这里是我的json文件的格式:使用Javascript连接SVG圈子
[{"sourceNode":"1","type":"sourceNode"},
{"sourceNode":"3","type":"sourceNode"},
{"sourceNode":"8","type":"sourceNode"},
.....
{"targetNode":"1","type":"targetNode"},
{"targetNode":"7","type":"targetNode"},
{"targetNode":"1","type":"targetNode"},
.....
{"type":"link","source":"1","target":"2"},
{"type":"link","source":"3","target":"4"},
{"type":"link","source":"3","target":"5"}]
我正在使用滴答功能给圆和线的属性。圆圈工作得很好,但当我检查我的SVG在html中时,我没有得到没有属性的行。
下面是代码:
var nodeSource = g.selectAll("circle")
.data(data.filter(function (d){ return d.type == "sourceNode"; }))
.enter().append("circle")
.attr("r", 5)
.style("fill", "blue")
.call(force.drag);
var nodeTarget = g.selectAll("rect")
.data(data.filter(function (d){ return d.type == "targetNode"; }))
.enter().append("rect")
.attr("width", 10)
.attr("height", 10)
.style("fill", "green")
.call(force.drag);
var link = g.selectAll("line")
.data(data.filter(function (d){ return d.type == "link"; }))
.enter().append("line")
.style("stroke-width", "2")
.style("stroke", "grey")
.call(force.drag);
function tick(e) {
nodeSource
.attr("cx", function(d) { return d.x = Math.max(radius(), Math.min(width() - radius(), d.x)); })
.attr("cy", function(d) { return d.y = Math.max(radius(), Math.min(height() - radius(), d.y)); });
nodeTarget
.attr("x", function(d) { return d.x = Math.max(radius(), Math.min(width() - radius(), d.x)); })
.attr("y", function(d) { return d.y = Math.max(radius(), Math.min(height() - radius(), d.y)); });
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; });
chart.draw()
}
答
当你分配x1
,x2
,坐标等你行,你就没有真正给他们的价值。在你的json文件中,链接的数据有:
"source": "1"
例如。使用d.source.anything
不会返回值,因为"1"
没有附加任何属性。如果你想获得到具有这个号码的节点的引用,你必须使用d3
找到它:
line.attr('x1', function (d) {
return d3.selectAll('circle').filter(function (k) {
return d.source === k.sourceNode;
}).attr('cx');
})
然后,当你想要做的目标节点:
line.attr('x2', function(d) {
return d3.selectAll('rect').filter(function (k) {
return d.target === k.targetNode;
}).attr('x');
})
你使用强制布局?你给force.nodes()做了什么?这似乎是force.nodes和force.links中的一个参考文件 –