2015-03-19 84 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