我刚刚开始使用 d3 library .我花了几天时间探索 api 并查看示例,并根据 force-directed graph 开始了我自己的项目。示例。
如果不使用简单的形状(正方形
、圆形
),我如何在 tick
之后更新节点的位置。 ..) 您正在使用路径绘制节点?
我提供了一个示例,您可以在此处查看:jsFiddle
var svg = d3.select('#view').attr({width: 300, height: 300});
var data = {
"nodes": [
{
"id": "node_0",
"name": "Node 0",
"color": "blue",
"h": 10,
"w": 20,
"t": "triangle"
},....
],
"links": [
{
"source": 0,
"target": 1
},...
]
};
var force = d3.layout.force().size([300, 300])
.linkDistance(50)
.nodes(data.nodes)
.links(data.links).start()
var link = svg.selectAll('.link').data(data.links).enter()
.append('line')
.attr('class', 'link')
.attr({"stroke": "#ccc", "stroke-width": 1.5});
var wrapper = svg.selectAll('.node').data(data.nodes).enter()
.append('g')
.attr('class', 'node')
.attr('x', function(d){return d.x})
.attr('y', function(d){return d.y});
var getShape = function(t, x, y, w, h){
var points = (t == 'triangle') ?
[ [x + w/2, y], [x + w/2 , y], [x + w, y + h], [x, y + h]]
:
[ [x, y], [x + w, y], [x + w, y + h], [x, y + h]];
return d3.svg.line()(points)
}
var node = wrapper.append('path')
.attr('d', function(d){return getShape(d.t, d.x , d.y, d.h, d.w) })
.attr('x', function(d){return d.x})
.attr('y', function(d){return d.y})
.attr('fill', function(d){return d.color})
.call(force.drag);
force.on('tick', function(){
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('cx', function(d){return d.x})
.attr('cy', function(d){return d.y});
});
最佳答案
对于一般形状,您可以简单地使用 transform
属性相应地移动节点,参见例如this example .
关于javascript - D3 力向图 : update node position,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18512225/