我是d3的新手,在缩放和拖动树形布局时遇到了麻烦。
编辑:使用评论信息
更新了JSFiddle我创建了一个示例JSFiddle here。
我的问题在于缩放功能:
function zoom() {
var scale = d3.event.scale,
translation = d3.event.translate,
tbound = -height * scale * 100,
bbound = height * scale,
lbound = (-width + margin.right) * scale,
rbound = (width - margin.bottom) * scale;
console.log("pre min/max" + translation);
// limit translation to thresholds
translation = [
Math.max(Math.min(translation[0], rbound), lbound),
Math.max(Math.min(translation[1], bbound), tbound)];
console.log("scale" + scale);
console.log("translation" + translation);
d3.select("g")
.attr("transform", "translate(" + translation + ")" +
" scale(" + scale + ")");
}
如果展开并折叠节点然后尝试拖动,则根节点始终返回到左上角。我添加了一些日志记录,显示在这种情况下translation
的值为-1,-1
有没有办法可以保留当前的根节点位置?
答案 0 :(得分:2)
问题是您使用缩放行为翻译的g
元素是使用非零转换初始化的。缩放行为不会意识到这一点,导致您看到“跳跃”。要修复此问题,请使用该转换初始化缩放行为。
var zb = d3.behavior.zoom().scaleExtent([0.5, 5]).on("zoom", function () {
zoom();
});
zb.translate([margin.left, margin.top]);
完整示例here。