如何使用d3的力布局平移到节点 [英] How to pan to a node using d3's force layout

查看:157
本文介绍了如何使用d3的力布局平移到节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

按名称搜索节点时,我想重点介绍一下.我正在尝试使用最新的方法来做到这一点....

I would like to focus on a node when it is searched for by name. I am trying to do this using a recenter method....

zoom = d3.behavior.zoom()
        .scaleExtent([.05, 10])
        .on("zoom", zoomed);
svg = d3.select("#graph")
        .append("svg")
        .attr("height", height)
        .attr("width", width)
        .call(zoom);
....
function zoomed(sel) {
    zoomBase(d3.event.translate , d3.event.scale);
}
function zoomBase(translate, scale){
    zoom.scale(scale);
    zoom.translate(translate);
    container.attr("transform", "translate(" + translate + ")scale(" + scale + ")");
}
function recenter(node){
    var node = findNodeByName(node);
    if(zoom.scale() < 0.5){
        zoom.scale(0.5);
    }
    zoom.translate([node.x, node.y]); // Math seems to be wrong here
    container.attr("transform", "translate(" + translate + ")scale(" + zoom.scale() + ")");
}

问题是,当我在有问题的节点上并对其进行搜索时,我的位置显示为[-2246.3690822841745, -846.6411913027562],但是当我从实际节点上获得x和y时,考虑到我在顶部,我得到了[4346.868560310511, 1950.790521658118].节点的位置,这里是否需要一些数学运算?

The problem is that when I am over the node in question and search for it my location shows up as [-2246.3690822841745, -846.6411913027562] but when I get the x and y off of the actual node I get [4346.868560310511, 1950.790521658118] considering I am over top of the node, is there some math or something I need here?

推荐答案

Lars是对的,这就是答案...

Lars was right this is the answer...

zoom.translate([width / 2 - zoom.scale() * node.x, height / 2 - zoom.scale() * node.y])

要打破这一点一点

width / 2 (go to middle) 
- 
zoom.scale() * node.x (move middle to the scaled x)

这篇关于如何使用d3的力布局平移到节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆