Javascript D3.js缩放和平移可折叠树图

Javascript D3.js缩放和平移可折叠树图,javascript,d3.js,zooming,pan,Javascript,D3.js,Zooming,Pan,我正在使用D3.js绘制一个可折叠的树形图,如图中所示。它工作得很好,但是当它进入正常功能时,图的大小可能会发生巨大的变化(即,我将拥有更多节点,而不是现在仅有的几个节点) 我想让SVG区域滚动,我已经尝试了我在网上找到的一切使它工作,但没有成功。我所做的最好的工作就是使用d3.behavior.drag,在其中我拖动了整个图表。它远不是最优的,而且有很多小故障,但它还是可以使用的 尽管如此,我还是尝试清理一下,我意识到根据API文档,d3.behavior.zoom也可以用来平移SVG区域 问

我正在使用D3.js绘制一个可折叠的树形图,如图中所示。它工作得很好,但是当它进入正常功能时,图的大小可能会发生巨大的变化(即,我将拥有更多节点,而不是现在仅有的几个节点)

我想让SVG区域滚动,我已经尝试了我在网上找到的一切使它工作,但没有成功。我所做的最好的工作就是使用
d3.behavior.drag
,在其中我拖动了整个图表。它远不是最优的,而且有很多小故障,但它还是可以使用的

尽管如此,我还是尝试清理一下,我意识到根据API文档,
d3.behavior.zoom
也可以用来平移SVG区域

问题:有人能解释一下如何使其适应我的代码吗

我希望能够用图表平移SVG区域,如果可能的话,使其对一些误用做出反应,即尝试将图表平移出视口,并启用缩放到最大视口尺寸

这是我目前的代码:

var realWidth = window.innerWidth;
var realHeight = window.innerHeight;

function load(){
    callD3();
}

var m = [40, 240, 40, 240],
    w = realWidth -m[0] -m[0],
    h = realHeight -m[0] -m[2],
    i = 0,
    root;

var tree = d3.layout.tree()
    .size([h, w]);

var diagonal = d3.svg.diagonal()
    .projection(function(d) { return [d.y, d.x]; });

var vis = d3.select("#box").append("svg:svg")
    .attr("class","svg_container")
    .attr("width", w)
    .attr("height", h)
    .style("overflow", "scroll")
    .style("background-color","#EEEEEE")
  .append("svg:g")
    .attr("class","drawarea")
    .attr("transform", "translate(" + m[3] + "," + m[0] + ")")
    ;

var botao = d3.select("#form #button");

function callD3() {
//d3.json(filename, function(json) {
d3.json("D3_NEWCO_tree.json", function(json) {
  root = json;
  d3.select("#processName").html(root.text);
  root.x0 = h / 2;
  root.y0 = 0;

  botao.on("click", function(){toggle(root); update(root);});

  update(root);  
});

function update(source) {
  var duration = d3.event && d3.event.altKey ? 5000 : 500;

  // Compute the new tree layout.
  var nodes = tree.nodes(root).reverse();

  // Normalize for fixed-depth.
  nodes.forEach(function(d) { d.y = d.depth * 50; });

  // Update the nodes…
  var node = vis.selectAll("g.node")
      .data(nodes, function(d) { return d.id || (d.id = ++i); });

  // Enter any new nodes at the parent's previous position.
  var nodeEnter = node.enter().append("svg:g")
      .attr("class", "node")
      .attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; })
      .on("click", function(d) { toggle(d); update(d); });

  nodeEnter.append("svg:circle")
        .attr("r", function(d){ 
                    return  Math.sqrt((d.part_cc_p*1))+4;
        })
      .attr("class", function(d) { return "level"+d.part_level; })
      .style("stroke", function(d){
        if(d._children){return "blue";}
      })    
      ;

  nodeEnter.append("svg:text")
      .attr("x", function(d) { return d.children || d._children ? -((Math.sqrt((d.part_cc_p*1))+6)+this.getComputedTextLength() ) : Math.sqrt((d.part_cc_p*1))+6; })
      .attr("y", function(d) { return d.children || d._children ? -7 : 0; })
      .attr("dy", ".35em")
      .attr("text-anchor", function(d) { return d.children || d._children ? "end" : "start"; })
      .text(function(d) { 
        if(d.part_level>0){return d.name;}
        else
            if(d.part_multi>1){return "Part " + d.name+ " ["+d.part_multi+"]";}
            else{return "Part " + d.name;}
         })
        .attr("title", 
            function(d){ 
                var node_type_desc;
                if(d.part_level!=0){node_type_desc = "Labour";}else{node_type_desc = "Component";}
                return ("Part Name: "+d.text+"<br/>Part type: "+d.part_type+"<br/>Cost so far: "+d3.round(d.part_cc, 2)+"&euro;<br/>"+"<br/>"+node_type_desc+" cost at this node: "+d3.round(d.part_cost, 2)+"&euro;<br/>"+"Total cost added by this node: "+d3.round(d.part_cost*d.part_multi, 2)+"&euro;<br/>"+"Node multiplicity: "+d.part_multi);
        })
      .style("fill-opacity", 1e-6);

  // Transition nodes to their new position.
  var nodeUpdate = node.transition()
      .duration(duration)
      .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; });

  nodeUpdate.select("circle")
        .attr("r", function(d){ 
            return  Math.sqrt((d.part_cc_p*1))+4;
        })
      .attr("class", function(d) { return "level"+d.part_level; })
      .style("stroke", function(d){
        if(d._children){return "blue";}else{return null;}
      })
      ;

  nodeUpdate.select("text")
      .style("fill-opacity", 1);

  // Transition exiting nodes to the parent's new position.
  var nodeExit = node.exit().transition()
      .duration(duration)
      .attr("transform", function(d) { return "translate(" + source.y + "," + source.x + ")"; })
      .remove();

    nodeExit.select("circle")
        .attr("r", function(d){ 
            return  Math.sqrt((d.part_cc_p*1))+4;
        });

  nodeExit.select("text")
      .style("fill-opacity", 1e-6);

  // Update the links…
  var link = vis.selectAll("path.link")
      .data(tree.links(nodes), function(d) { return d.target.id; });

  // Enter any new links at the parent's previous position.
  link.enter().insert("svg:path", "g")
      .attr("class", "link")
      .attr("d", function(d) {
        var o = {x: source.x0, y: source.y0};
        return diagonal({source: o, target: o});
      })
    .transition()
      .duration(duration)
      .attr("d", diagonal);

  // Transition links to their new position.
  link.transition()
      .duration(duration)
      .attr("d", diagonal);

  // Transition exiting nodes to the parent's new position.
  link.exit().transition()
      .duration(duration)
      .attr("d", function(d) {
        var o = {x: source.x, y: source.y};
        return diagonal({source: o, target: o});
      })
      .remove();

    $('svg text').tipsy({
        fade:true,
        gravity: 'nw', 
        html:true
    });

  // Stash the old positions for transition.
  nodes.forEach(function(d) {
    d.x0 = d.x;
    d.y0 = d.y;
  });

    var drag = d3.behavior.drag()
        .origin(function() { 
            var t = d3.select(this);
            return {x: t.attr("x"), y: t.attr("y")};
        })
        .on("drag", dragmove);

    d3.select(".drawarea").call(drag);

}

// Toggle children.
function toggle(d) {
  if (d.children) {
    d._children = d.children;
    d.children = null;
  } else {
    d.children = d._children;
    d._children = null;
  }

}

function dragmove(){
    d3.transition(d3.select(".drawarea"))
    .attr("transform", "translate(" + d3.event.x +"," + d3.event.y + ")"); 
}
}
var realWidth=window.innerWidth;
var realHeight=window.innerHeight;
函数加载(){
callD3();
}
var m=[40,240,40,240],
w=realWidth-m[0]-m[0],
h=真实高度-m[0]-m[2],
i=0,
根;
var tree=d3.layout.tree()
.尺寸([h,w]);
var diagonal=d3.svg.diagonal()
.投影(函数(d){返回[d.y,d.x];});
var vis=d3.选择(#框”).追加(“svg:svg”)
.attr(“类”、“svg_容器”)
.attr(“宽度”,w)
.attr(“高度”,h)
.style(“溢出”、“滚动”)
.style(“背景色”,“EEEEEE”)
.append(“svg:g”)
.attr(“类”、“绘图区”)
.attr(“转换”、“转换”(+m[3]+“,+m[0]+”)
;
var botao=d3.选择(“表单按钮”);
函数callD3(){
//d3.json(文件名、函数(json){
json(“d3_NEWCO_tree.json”,函数(json){
root=json;
d3.选择(“#processName”).html(root.text);
root.x0=h/2;
root.y0=0;
打开(“单击”,函数(){切换(根);更新(根);});
更新(根);
});
函数更新(源){
var持续时间=d3.event&&d3.event.altKey?5000:500;
//计算新的树布局。
var nodes=tree.nodes(root.reverse();
//为固定深度进行规格化。
forEach(函数(d){d.y=d.depth*50;});
//更新节点…
var node=vis.selectAll(“g.node”)
.data(节点,函数(d){返回d.id | |(d.id=++i)});
//在父节点的上一个位置输入任何新节点。
var nodeEnter=node.enter().append(“svg:g”)
.attr(“类”、“节点”)
.attr(“transform”,函数(d){return“translate”(“+source.y0+”,“+source.x0+”));})
.on(“单击”,函数(d){切换(d);更新(d);});
追加(“svg:circle”)
.attr(“r”,函数(d){
返回数学sqrt((d.part_cc_p*1))+4;
})
.attr(“类”,函数(d){return“level”+d.part_level;})
.样式(“笔划”,功能(d){
如果(d._儿童){返回“蓝色”;}
})    
;
追加(“svg:text”)
.attr(“x”,函数(d){return d.children | | d._children?-((Math.sqrt((d.part_cc_p*1))+6)+this.getComputedTextLength()):Math.sqrt((d.part_cc_p*1))+6;)
.attr(“y”,函数(d){返回d.children | | d._children?-7:0;})
.attr(“dy”,“.35em”)
.attr(“文本锚定”,函数(d){return d.children | | d.| u children?“end”:“start”})
.text(功能(d){
如果(d.part_level>0){返回d.name;}
其他的
如果(d.part_multi>1){返回“part”+d.name+“[”+d.part_multi+“]”;}
else{return“Part”+d.name;}
})
.attr(“标题”,
函数(d){
变量节点类型描述;
如果(d.part_level!=0){node_type_desc=“Labour”}否则{node_type_desc=“Component”}
return(“零件名称:”+d.text+“
零件类型:”+d.Part\u类型+“
到目前为止的成本:”+d3.round(d.Part\u cc,2)+“&euro;
“+node\u类型描述+”此节点的成本:“+d3.round(d.Part\u成本,2)+”&euro;
“+”此节点添加的总成本:“+d3.round(d.Part\u成本*d.Part\u多重性:”
”; }) .样式(“填充不透明度”,1e-6); //将节点转换到其新位置。 var nodeUpdate=node.transition() .持续时间(持续时间) .attr(“转换”,函数(d){return“translate”(+d.y+),“+d.x+”);}); 节点更新。选择(“圆圈”) .attr(“r”,函数(d){ 返回数学sqrt((d.part_cc_p*1))+4; }) .attr(“类”,函数(d){return“level”+d.part_level;}) .样式(“笔划”,功能(d){ if(d._children){return“blue”}else{return null;} }) ; nodeUpdate.select(“文本”) .样式(“填充不透明度”,1); //将退出节点转换到父节点的新位置。 var nodeExit=node.exit().transition() .持续时间(持续时间) .attr(“transform”,函数(d){return“translate”(“+source.y+”,“+source.x+”)”);}) .remove(); nodeExit.select(“圆”) .attr(“r”,函数(d){ 返回数学sqrt((d.part_cc_p*1))+4; }); nodeExit.select(“文本”) .样式(“填充不透明度”,1e-6); //更新链接… var link=vis.selectAll(“path.link”) .data(tree.links(节点),函数(d){return d.target.id;}); //在父对象的上一个位置输入任何新链接。 link.enter().insert(“svg:path”,“g”) .attr(“类”、“链接”) .attr(“d”,函数(d){ var o={x:source.x0,y:source.y0}; 返回对角线({source:o,target:o}); }) .transition() .持续时间(持续时间) .attr(“d”,对角线); //过渡链接到他们的新位置。 link.transition() .持续时间(持续时间) .attr(“d”,对角线); //将退出节点转换到父节点的新位置。 link.exit().transition() .持续时间(持续时间) .attr(“d”,函数(d){ 变量o={
d3.select("svg")
    .call(d3.behavior.zoom()
      .scaleExtent([0.5, 5])
      .on("zoom", zoom));
function zoom() {
    var scale = d3.event.scale,
        translation = d3.event.translate,
        tbound = -h * scale,
        bbound = h * scale,
        lbound = (-w + m[1]) * scale,
        rbound = (w - m[3]) * scale;
    // limit translation to thresholds
    translation = [
        Math.max(Math.min(translation[0], rbound), lbound),
        Math.max(Math.min(translation[1], bbound), tbound)
    ];
    d3.select(".drawarea")
        .attr("transform", "translate(" + translation + ")" +
              " scale(" + scale + ")");
}
vis // snip
  .append("svg:g")
    .attr("class","drawarea")
  .append("svg:g")
    .attr("transform", "translate(" + m[3] + "," + m[0] + ")");