2015-06-21 40 views
0

這是相當簡單的,以創建在D3一些文本,並讓它換行:D3自動換行與數據驅動寬度限制

var textElement = svg.selectAll('text') 
        .data(myData) 
        .enter() 
        .append('text') 
        .text(someVeryLongText) 
        .call(wrapText, allowedWidth); 

的wrapText()函數是使用的相當標準的實施例在那裏一個實現(例如http://bl.ocks.org/mbostock/7555321)。

我的問題是,當我想爲每個文本字段依賴於數據的允許寬度,這樣的:

    ... 
        .text(someVeryLongText) 
        .call(wrapText, function(d) { 
        return d.someCondition ? 100 : 200; 
        }); 

是這樣的可能嗎?

回答

0

調整您鏈接的示例中的包裝功能,如下所示,並在您的帖子中使用所需的呼叫簽名。工作示例here

function wrap(text, width) { 
    text.each(function(d, i/*[edit]*/) { 
     var text = d3.select(this), 
      words = text.text().split(/\s+/).reverse(), 
      word, 
      line = [], 
      lineNumber = 0, 
      lineHeight = 1.1, // 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"), 
      //[edit]add dWidth 
      dWidth = typeof width === "function" ? width(d, i) : width; 
     while (word = words.pop()) { 
      line.push(word); 
      tspan.text(line.join(" ")); 
      if (tspan.node().getComputedTextLength() > dWidth/*[edit]*/) { 
       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); 
      } 
     } 
    }); 
} 
+0

棒極了!謝謝:-) – ThisRestlessPilgrim

+0

只要記住,在目前的形式下,如果已經存在tspan元素,它將會中斷。但如果你稍微調整一下,很容易修復。 –