2015-03-19 52 views
3

我想将长文本元素包装为宽度。这里的例子取自Bostock's wrap function,但似乎有两个问题:首先,wrap的结果没有继承元素的x值(文本左移);其次它包装在同一条线上,并且lineHeight参数不起作用。在d3.js中包装长文本

感谢您的建议。 http://jsfiddle.net/geotheory/bk87ja3g/

var svg = d3.select("body").append("svg") 
    .attr("width", 300) 
    .attr("height", 300) 
    .style("background-color", '#ddd'); 

dat = ["Ukip has peaked, but no one wants to admit it - Nigel Farage now resembles every other politician", 
     "Ashley Judd isn't alone: most women who talk about sport on Twitter face abuse", 
     "I'm on list to be a Mars One astronaut - but I won't see the red planet"]; 

svg.selectAll("text").data(dat).enter().append("text") 
    .attr('x', 25) 
    .attr('y', function(d, i){ return 30 + i * 90; }) 
    .text(function(d){ return d; }) 
    .call(wrap, 250); 

function wrap(text, width) { 
    text.each(function() { 
     var text = d3.select(this), 
     words = text.text().split(/\s+/).reverse(), 
     word, 
     line = [], 
     lineNumber = 1, 
     lineHeight = 1.2, // ems 
     y = text.attr("y"), 
     dy = parseFloat(text.attr("dy")), 
     tspan = text.text(null).append("tspan").attr("x", 0).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", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word); 
      } 
     } 
    }); 
} 

回答

3

博斯托克的原始函数假定text元件具有初始dy集。它还会删除text上的任何x属性。最后,您将wrap函数更改为从lineNumber = 1开始,该函数需要为0

重构了一下:

function wrap(text, width) { 
    text.each(function() { 
     var text = d3.select(this), 
     words = text.text().split(/\s+/).reverse(), 
     word, 
     line = [], 
     lineNumber = 0, //<-- 0! 
     lineHeight = 1.2, // ems 
     x = text.attr("x"), //<-- include the x! 
     y = text.attr("y"), 
     dy = text.attr("dy") ? text.attr("dy") : 0; //<-- null check 
     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); 
      } 
     } 
    }); 
} 

更新fiddle

+0

谢谢马克,这解决了这两个问题 – geotheory 2015-03-19 13:37:48

3

的问题是这一行:

dy = parseFloat(text.attr("dy")) 

在这个例子中,你已经挂,dy设置在text的元素,但不是在你的情况。所以你得到NaN那反过来导致的dyNaN。通过向dy如果NaN分配0修复:

dy = parseFloat(text.attr("dy")) || 0 

完成演示here