Подтвердить что ты не робот

Обтекание текста в D3

Я хочу, чтобы текст обернулся на следующем дереве D3, чтобы вместо

Foo is not a long word

каждая строка завернута в

Foo is
not a
long word

Я попытался сделать текст "foreignObject", а не текстовым, и текст действительно обернут, но он не перемещается по анимации дерева и сгруппирован в верхнем левом углу.

Код, расположенный в

http://jsfiddle.net/mikeyai/X43X5/1/

JavaScript:

var width = 960,
    height = 500;

var tree = d3.layout.tree()
    .size([width - 20, height - 20]);

var root = {},
    nodes = tree(root);

root.parent = root;
root.px = root.x;
root.py = root.y;

var diagonal = d3.svg.diagonal();

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height)
  .append("g")
    .attr("transform", "translate(10,10)");

var node = svg.selectAll(".node"),
    link = svg.selectAll(".link");

var duration = 750,
    timer = setInterval(update, duration);

function update() {
  if (nodes.length >= 500) return clearInterval(timer);

  // Add a new node to a random parent.
  var n = {id: nodes.length},
      p = nodes[Math.random() * nodes.length | 0];
  if (p.children) p.children.push(n); else p.children = [n];
  nodes.push(n);

  // Recompute the layout and data join.
  node = node.data(tree.nodes(root), function(d) { return d.id; });
  link = link.data(tree.links(nodes), function(d) { return d.source.id + "-" + d.target.id; });

  // Add entering nodes in the parent’s old position.
  node.enter().append("text")
      .attr("class", "node")
      .attr("x", function(d) { return d.parent.px; })
      .attr("y", function(d) { return d.parent.py; })
        .text('Foo is not a long word');

  // Add entering links in the parent’s old position.
  link.enter().insert("path", ".node")
      .attr("class", "link")
      .attr("d", function(d) {
        var o = {x: d.source.px, y: d.source.py};
        return diagonal({source: o, target: o});
      });

  // Transition nodes and links to their new positions.
  var t = svg.transition()
      .duration(duration);

  t.selectAll(".link")
      .attr("d", diagonal);

  t.selectAll(".node")
      .attr("x", function(d) { return d.px = d.x; })
      .attr("y", function(d) { return d.py = d.y; });
}
4b9b3361

Ответ 1

Вы можете изменить Mike Bostock пример "Wrapping Long Labels", чтобы добавить элементы <tspan> в ваши узлы <text>. Для добавления обернутого текста в ваши узлы необходимы два основных изменения. Я не хотел, чтобы текст обновлял свою позицию во время переходов, но добавить его не должно быть слишком сложно.

Во-первых, это добавить функцию wrap, основанную на функции из вышеприведенного примера. wrap позаботится о добавлении элементов <tspan>, чтобы ваш текст помещался на определенной ширине:

function wrap(text, width) {
    text.each(function () {
        var text = d3.select(this),
            words = "Foo is not a long word".split(/\s+/).reverse(),
            word,
            line = [],
            lineNumber = 0,
            lineHeight = 1.1, // ems
            x = text.attr("x"),
            y = text.attr("y"),
            dy = 0, //parseFloat(text.attr("dy")),
            tspan = text.text(null)
                        .append("tspan")
                        .attr("x", x)
                        .attr("y", y)
                        .attr("dy", dy + "em");
        while (word = words.pop()) {
            line.push(word);
            tspan.text(line.join(" "));
            if (tspan.node().getComputedTextLength() > width) {
                line.pop();
                tspan.text(line.join(" "));
                line = [word];
                tspan = text.append("tspan")
                            .attr("x", x)
                            .attr("y", y)
                            .attr("dy", ++lineNumber * lineHeight + dy + "em")
                            .text(word);
            }
        }
    });
}

Второе изменение заключается в том, что вместо установки текста каждого узла вам нужно вызвать wrap для каждого узла:

// Add entering nodes in the parents old position.
node.enter().append("text")
    .attr("class", "node")
    .attr("x", function (d) { return d.parent.px; })
    .attr("y", function (d) { return d.parent.py; })
    .call(wrap, 30); // wrap the text in <= 30 pixels

Ответ 2

Другой вариант, если вы хотите добавить еще одну библиотеку JS, - это использовать D3plus, аддон D3. Он имеет встроенную функцию переноса текста. Он даже поддерживает заполнение и изменение размера текста, чтобы заполнить доступное пространство.

d3plus.textwrap()
  .container(d3.select("#rectWrap"))
  .draw();

Я использовал это. Это, конечно, лучше, чем рассчитывать упаковку самостоятельно.

Существует другой плагин d3, доступный для переноса текста, но я никогда не использовал его, поэтому не могу говорить о его полезности.

Ответ 3

Это способ переноса текста с помощью d3 plus. Это действительно легко для меня и работает во всех браузерах на данный момент

d3plus.textwrap()
    .container(d3.select("#intellectual"))
    .shape('square')
    .width(370)
    .height(55)
    .resize(true)
    .draw();