2016-11-04 4 views
1

Я использую d3 js для свертывания дерева. Я хочу исправить ширину прямоугольника. Если размер текста в прямоугольной области больше, чем фиксированная ширина прямоугольной коробки, как динамически увеличить высоту прямоугольной ячейки?Как увеличить высоту динамически, установив ширину прямоугольника в d3 js

Как показано ниже, я хочу выход. enter image description here

Вот код, что я использую

.node { 
 
\t \t cursor: pointer; 
 
\t \t border-style: solid; 
 
    border-width: 2px 10px 4px 20px; 
 
\t } 
 

 
\t .node circle { 
 
\t fill: #fff; 
 
\t stroke: steelblue; 
 
\t stroke-width: 3px; 
 
\t } 
 
\t 
 
\t .node rect { 
 
\t fill: #fff; 
 
\t stroke: steelblue; 
 
\t stroke-width: 3px; 
 
\t } 
 

 
\t .node text { 
 
\t font: 12px sans-serif; 
 
\t } 
 

 
\t .link { 
 
\t fill: none; 
 
\t stroke: #ccc; 
 
\t stroke-width: 2px; 
 
\t }
<!-- load the d3.js library --> \t 
 
<script src="https://d3js.org/d3.v3.min.js"></script> 
 
\t 
 
<script> 
 

 
var treeData = [ 
 
    { 
 
    "name": "Top Level", 
 
    "parent": "null", 
 
    "children": [ 
 
     { 
 
     "name": "Level 2: A. Some text here Some text here Some text here", 
 
     "parent": "Top Level", 
 
     "children": [ 
 
      { 
 
      "name": "Son of A", 
 
      "parent": "Level 2: A" 
 
      }, 
 
      { 
 
      "name": "Daughter of A", 
 
      "parent": "Level 2: A" 
 
      } 
 
     ] 
 
     }, 
 
     { 
 
     "name": "Level 2: B", 
 
     "parent": "Top Level" 
 
\t \t 
 
     } 
 
    ] 
 
    } 
 
]; 
 

 

 
// ************** Generate the tree diagram \t ***************** 
 
var margin = {top: 20, right: 120, bottom: 20, left: 120}, 
 
\t width = 960 - margin.right - margin.left, 
 
\t height = 500 - margin.top - margin.bottom; 
 
\t 
 
var i = 0, 
 
\t duration = 750, 
 
\t root; 
 

 
var tree = d3.layout.tree() 
 
\t .size([height, width]); 
 

 

 
var diagonal = d3.svg.diagonal() 
 
     .source(function (d) { 
 
      return { 
 
       "x": d.source.x, 
 
       "y": d.source.y + 150 
 
      }; 
 
     }) 
 
     .projection(function (d) { return [d.y + 0, d.x + 0]; 
 
     }); 
 

 
var svg = d3.select("body").append("svg") 
 
\t .attr("width", width + margin.right + margin.left) 
 
\t .attr("height", height + margin.top + margin.bottom) 
 
    .append("g") 
 
\t .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); 
 

 
root = treeData[0]; 
 
root.x0 = height/2; 
 
root.y0 = 0; 
 
    
 
update(root); 
 

 
d3.select(self.frameElement).style("height", "500px"); 
 

 
function update(source) { 
 

 
    // Compute the new tree layout. 
 
    var nodes = tree.nodes(root).reverse(), 
 
\t links = tree.links(nodes); 
 

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

 
    // Update the nodes… 
 
    var node = svg.selectAll("g.node") 
 
\t .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("g") 
 
\t .attr("class", "node") 
 
\t .attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; }) 
 
\t .on("click", click); 
 

 
    nodeEnter.append("rect") 
 
\t .attr("x", function(d) { return d.children || d._children ? 0 : 0; }) 
 
\t .attr("y", function(d) { return d.children || d._children ? 15 : 15; }) 
 
\t .attr("rx", 10) 
 
\t .attr("ry", 10) 
 
    .attr("width", 10) 
 
    .attr("height", 10) 
 
\t .style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; }); 
 

 
    nodeEnter.append("text") 
 
\t .attr("x", 60) 
 
\t .attr("dy", ".35em") 
 
\t .attr("text-anchor", "middle") 
 
\t .text(function(d) { return d.name; }) 
 
\t .style("fill-opacity", 1e-6); 
 

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

 
    nodeUpdate.select("rect") 
 
\t .attr("x", function(d) { return d.children || d._children ? 0 : 0; }) 
 
\t .attr("y", function(d) { return d.children || d._children ? -15 : -15; }) 
 
\t .attr("rx", 10) 
 
\t .attr("ry", 10) 
 
    .attr("width", 150) 
 
    .attr("height", 30) 
 
\t .style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; }); 
 

 
    nodeUpdate.select("text") 
 
\t .style("fill-opacity", 1) 
 
.attr("text-anchor", "middle"); 
 

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

 
    nodeExit.select("rect") 
 
\t .attr("x", function(d) { return d.children || d._children ? 0 : 0; }) 
 
\t .attr("y", function(d) { return d.children || d._children ? 15 : 15; }) 
 
\t .attr("rx", 10) 
 
\t .attr("ry", 10) 
 
    .attr("width", 10) 
 
    .attr("height", 10); 
 

 
    nodeExit.select("text") 
 
\t .style("fill-opacity", 1e-6) 
 
\t \t .attr("text-anchor", "middle"); 
 

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

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

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

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

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

 
// Toggle children on click. 
 
function click(d) { 
 
    if (d.children) { 
 
\t d._children = d.children; 
 
\t d.children = null; 
 
    } else { 
 
\t d.children = d._children; 
 
\t d._children = null; 
 
    } 
 
    update(d); 
 
} 
 

 
</script>

ответ

0

Просто поверхностная попытка.

  1. Сначала добавьте все текстовые элементы
  2. Wrap текстовый элемент в определенной ширины, используя tspans
  3. Получить высоту текстового элемента и хранить в качестве атрибута его в самих данных
  4. Использование хранимая атрибут для установки высоты прямоугольника

Ссылка для обертывания текста here. Вы всегда можете написать пользовательскую функцию упаковки.

Надеется, что это помогает

var treeData = [ 
 
    { 
 
    "name": "Top Level", 
 
    "parent": "null", 
 
    "children": [ 
 
     { 
 
     "name": "Level 2: A. Some text here Some text here Some text here Some text here", 
 
     "parent": "Top Level", 
 
     "children": [ 
 
      { 
 
      "name": "Son of A Some text here Some text here", 
 
      "parent": "Level 2: A" 
 
      }, 
 
      { 
 
      "name": "Daughter of A Some text here Some text here Some text here Some text here Some text here", 
 
      "parent": "Level 2: A" 
 
      } 
 
     ] 
 
     }, 
 
     { 
 
     "name": "Level 2: B Some text here Some text here Some text here", 
 
     "parent": "Top Level" 
 
\t \t 
 
     } 
 
    ] 
 
    } 
 
]; 
 

 

 
// ************** Generate the tree diagram \t ***************** 
 
var margin = {top: 20, right: 120, bottom: 20, left: 120}, 
 
\t width = 960 - margin.right - margin.left, 
 
\t height = 500 - margin.top - margin.bottom; 
 
\t 
 
var i = 0, 
 
\t duration = 750, 
 
\t root; 
 

 
var tree = d3.layout.tree() 
 
\t .size([height, width]); 
 

 

 
var diagonal = d3.svg.diagonal() 
 
     .source(function (d) { 
 
      return { 
 
       "x": d.source.x, 
 
       "y": d.source.y + 150 
 
      }; 
 
     }) 
 
     .projection(function (d) { return [d.y + 0, d.x + 0]; 
 
     }); 
 

 
var svg = d3.select("body").append("svg") 
 
\t .attr("width", width + margin.right + margin.left) 
 
\t .attr("height", height + margin.top + margin.bottom) 
 
    .append("g") 
 
\t .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); 
 

 
root = treeData[0]; 
 
root.x0 = height/2; 
 
root.y0 = 0; 
 
    
 
update(root); 
 

 
d3.select(self.frameElement).style("height", "500px"); 
 

 
function update(source) { 
 

 
    // Compute the new tree layout. 
 
    var nodes = tree.nodes(root).reverse(), 
 
\t links = tree.links(nodes); 
 

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

 
    // Update the nodes… 
 
    var node = svg.selectAll("g.node") 
 
\t .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("g") 
 
\t .attr("class", "node") 
 
\t .attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; }) 
 
\t .on("click", click); 
 

 
    nodeEnter.append("rect") 
 
\t .attr("x", function(d) { return d.children || d._children ? 0 : 0; }) 
 
\t .attr("y", function(d) { return d.children || d._children ? 15 : 15; }) 
 
\t .attr("rx", 10) 
 
\t .attr("ry", 10) 
 
    .attr("width", 10) 
 
    .attr("height", 10) 
 
\t .style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; }); 
 

 
    nodeEnter.append("text") 
 
\t .attr("x", 60) 
 
\t .attr("dy", ".35em") 
 
\t .attr("text-anchor", "middle") 
 
\t .text(function(d) { return d.name; }) 
 
\t .style("fill-opacity", 1e-6) 
 
    \t .each(function(d) { 
 
    \t \t calculateTextWrap(this,d); 
 
    \t \t }); 
 

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

 
    nodeUpdate.select("rect") 
 
\t .attr("x", function(d) { return d.children || d._children ? 0 : 0; }) 
 
\t .attr("y", function(d) { return d.children || d._children ? -15 : -15; }) 
 
\t .attr("rx", 10) 
 
\t .attr("ry", 10) 
 
    .attr("width", 150) 
 
    .attr("height", function(d) { return d.rectHeight}) 
 
\t .style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; }); 
 

 
    nodeUpdate.select("text") 
 
\t .style("fill-opacity", 1) 
 
.attr("text-anchor", "middle"); 
 

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

 
    nodeExit.select("rect") 
 
\t .attr("x", function(d) { return d.children || d._children ? 0 : 0; }) 
 
\t .attr("y", function(d) { return d.children || d._children ? 15 : 15; }) 
 
\t .attr("rx", 10) 
 
\t .attr("ry", 10) 
 
    .attr("width", 10) 
 
    .attr("height", 10); 
 

 
    nodeExit.select("text") 
 
\t .style("fill-opacity", 1e-6) 
 
\t \t .attr("text-anchor", "middle"); 
 

 
\t function calculateTextWrap(element, data) { 
 
        var text = d3.select(element); 
 
        if (text.node().getComputedTextLength() < 150) { 
 
         //console.log("No need to wrap"); 
 
        } else { 
 
         var words = text.text().split("").reverse(), 
 
          word, 
 
          line = [], 
 
          lineNumber = 0, 
 
          lineHeight = 1.1, // ems 
 
          y = text.attr("y"), 
 
          dy = parseFloat(0.35), 
 
          tspan = text.text(null).append("tspan").attr("text-anchor", "start").attr("x", 5).attr("y", y).attr("dy", dy + "em"); 
 

 
         while (word = words.pop()) { 
 
          line.push(word); 
 
          tspan.text(line.join("")); 
 
          if (tspan.node().getComputedTextLength() > 150) { 
 
           lineNumber++; 
 
           line.pop(); 
 
           tspan.text(line.join("")); 
 
           line = [word]; 
 
           tspan = text.append("tspan").attr("text-anchor", "start").attr("x", 5).attr("y", y).attr("dy", lineHeight + dy + "em").text(word); 
 
          } 
 
         } 
 
        } 
 
\t \t \t \t var rectHeight = text.node().getBBox().height; 
 
\t \t \t \t \t if(rectHeight < 30) rectHeight = 30; 
 
\t \t \t \t data.rectHeight = rectHeight + 10 ; 
 
       } 
 
\t 
 
\t 
 
    // Update the links… 
 
    var link = svg.selectAll("path.link") 
 
\t .data(links, function(d) { return d.target.id; }); 
 

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

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

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

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

 
// Toggle children on click. 
 
function click(d) { 
 
    if (d.children) { 
 
\t d._children = d.children; 
 
\t d.children = null; 
 
    } else { 
 
\t d.children = d._children; 
 
\t d._children = null; 
 
    } 
 
    update(d); 
 
}
.node { 
 
\t \t cursor: pointer; 
 
\t \t border-style: solid; 
 
    border-width: 2px 10px 4px 20px; 
 
\t } 
 

 
\t .node circle { 
 
\t fill: #fff; 
 
\t stroke: steelblue; 
 
\t stroke-width: 3px; 
 
\t } 
 
\t 
 
\t .node rect { 
 
\t fill: #fff; 
 
\t stroke: steelblue; 
 
\t stroke-width: 3px; 
 
\t } 
 

 
\t .node text { 
 
\t font: 12px sans-serif; 
 
\t } 
 

 
\t .link { 
 
\t fill: none; 
 
\t stroke: #ccc; 
 
\t stroke-width: 2px; 
 
\t }
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.0/d3.min.js"></script>

Смежные вопросы