2017-01-03 106 views
1

我正在使用平移和縮放功能實現d3樹版本4。爲了使版本3的節點居中,我從版本3的例子中找到以下內容。如何在D3.js版本4中執行節點的居中?

// Function to center node when clicked/dropped so node doesn't get lost when collapsing/moving with large amount of children. 

function centerNode(source) { 
    scale = zoomListener.scale(); 
    x = -source.y0; 
    y = -source.x0; 
    x = x * scale + viewerWidth/2; 
    y = y * scale + viewerHeight/2; 
    d3.select('g').transition() 
     .duration(duration) 
     .attr("transform", "translate(" + x + "," + y + ")scale(" + scale + ")"); 
    zoomListener.scale(scale); 
    zoomListener.translate([x, y]); 
} 

我已在版本4

 _treeChanged: function() { 
    console.log(this.localName + '#' + this.id + ' tree data has changed'); 
    // Assigns parent, children, height, depth 
    var aa = this.$.polymerTree.getBoundingClientRect(); 
    var svg_height = aa.height - 20 - 30; 
    var svg_width = aa.width - 90 - 90; 
    this.root = d3.hierarchy(this.tree, function(d) { return d.children; }); 
    this.root.x0 = svg_height/2; 
    this.root.y0 = 0; 

    if (g) { 
     g.remove(); 
    } 

    zoomListener = d3.zoom() 
         .scaleExtent([.5, 10]) 
         .on("zoom", function() { 
          g.attr("transform", d3.event.transform); 
         } 
        ); 

    g = d3.select(this.$.polymerTree) 
      .call(zoomListener) 
      .on("dblclick.zoom", null) 
      .append("g"); 

    if (this.treemap) { 
     this.update(this.root); 
     this.centerNode(this.root); 
    } 
    }, 

下面我應該如何實現中心節點與第4版的工作?

我的工作D3樹是https://github.com/powerxhub/emh-d3-tree

謝謝!

回答

0

我發現我自己的解決辦法:

 centerNode: function(source) { 
    var aa = d3Polymer.$.polymerTree.getBoundingClientRect(); 
    var svg_height = aa.height - 20 - 30; 
    var svg_width = aa.width - 90 - 90; 

    t = d3.zoomTransform(d3Polymer.$.polymerTree); 

    /* 
     To keep the node to be centered at the same x coordinate use 
     x = t.x; 

     To position the node at a certain x coordinate, use 
     x = source.y0; 
     x = -x *t.k + 50; 

    */ 
    x = t.x; 
    y = source.x0; 

    y = -y *t.k + svg_height/2; 

    g.transition() 
    .duration(750) 
    .attr("transform", "translate(" + x + "," + y + ")scale(" + t.k + ")") 
    .on("end", function(){ g.call(zoomListener.transform, d3.zoomIdentity.translate(x,y).scale(t.k))}); 
    }, 

我得到了它的相關帖子在d3.js rewriting zoom example in version4

您從添加了縮放的元素調用zoomTransform可以得到t。就我而言,它直接在SVG上。 g是具有邊界SVG g分量的元素。下面是設置了變焦代碼:。

 zoomListener = d3.zoom() 
         .scaleExtent([.5, 10]) 
         .on("zoom", function() { 
          g.attr("transform", d3.event.transform); 
         } 
        ); 

    g = d3.select(this.$.polymerTree) 
      .call(zoomListener) 
      .on("dblclick.zoom", null) 
      .append("g"); 

這個$ polymerTree是SVG元素。