在 d3 强制布局中将节点放置在屏幕中央

Placing the nodes in the center of screen in d3 force layout

如何在 d3.js 中将节点放置在力布局的中心。 我在这里得到 JSON 数据,就像这样

"nodes": [{
    "cName": "User",
    "cImage_url": "/final/images/component_icons/user_image.png",
    "x": 49.99999999999999,
    "y": 150,
    "fixed": true
}, {
    "cType": "Oracle WebLogic",
    "cName": "weblogic177:7001",
    "cImage_url": "/final/images/Light/component_icons/APPLICATION_SERVERS.png",
    "x": 167,
    "y": 150,
    "fixed": true,
    "AlarmPopup": "WebLogic_server:weblogic177:7001",
    "cStateImage_url": "/final/images/Light/state20_INTERMEDIATE.png",
    "linktoLayermodel": "/final/monitor/EgDispLayers.jsp?site=egurkha.physical.topology&qctr=0&host=weblogic177:7001&comptype=Oracle WebLogic&comeFrom=topology&To=layerMode&isFromZone=null&iszoneName=&parentZone=null&tab=LayerModel&toDashBoardLayer=true"
}, {
    "cType": "Group",
    "cName": "hari11",
    "cImage_url": "/final/images/component_icons/group.png",
    "x": 283.99999999999994,
    "y": 49.99999999999999,
    "fixed": true,
    "AlarmPopup": "Group:hari11:NULL",
    "cStateImage_url": "/final/images/Light/state20_LOW.png",
    "linktoLayermodel": "/final/monitor/EgDisplayGroups.jsp?ptype=group&showsitesegments=false&group=hari11&serverType=Group&site=egurkha.physical.topology&segmentName=sample&fromHomepage=true"
}..

所以节点总是从屏幕的左角开始,但我需要从中心开始。

那么我如何操作 JSON 数据中的现有 x、y?

正是拉尔斯所说的。

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

这会将第一个节点放在屏幕中间(nodes[0] 表示第一个节点),如果您希望所有节点都向右移动,请执行以下操作:

var movement = 200;

    node.attr("transform", function(d)
    { 
    return "translate(" + movement + "," + 0 + ")"; }); //Here you move the nodes
        ;

这基本上遍历节点并将每个节点向右移动 200 像素。 我对链接做了同样的事情:

link.attr("transform", function(d)
        { 
        return "translate(" + movement + "," + 0 + ")"; }); //Here you move the links
            ;

已更新 JSFiddle:http://jsfiddle.net/aVhd8/159/