2015-01-12 43 views
1

使用D3創建一個力圖。我想單擊一個按鈕並出現一個矩形(我已經完成)。 現在我想用這幾行文字附加這個矩形文本。如何使用SVG文本元素進行換行符?

我有三個句子我希望顯示,每行一個,所以我知道斷行應該在哪裏。

我嘗試了這些:

.text("test" + "\n" + "should be on second line"); 

.text("test" + "\\n" + "should be on second line"); 

.text("test" + "<br/>" + "should be on second line"); 

.html("test" + "\n" + "should be on second line"); 

.html("test" + "\\n" + "should be on second line"); 

.html("test" + "<br/>" + "should be on second line"); 

他們都不似乎工作,而且我不確定爲什麼。我已經四處搜尋,人們都在做黑客來解決這個問題。當然有更簡單的方法?

+0

是不是http://bl.ocks.org/mbostock/4062045? –

+0

耶@NitishKumar但這並不重要。我想要做的就是編輯一個svg上的文本:rect在多行上有文本 – rekoDolph

+0

http://stackoverflow.com/questions/4991171/auto-line-wrapping-in-svg-text –

回答

2

我已經想出了它,併爲我工作,因爲我使用D3。我創建了一個數組(我希望顯示的文本),然後創建了一個函數,將數組拆分爲單獨的行。

var popUpTextArray = ["first line", "second line", "third line"]; 

function textMultipleRows(textArray, area, xPos, yPos){ 

    for(i=0;i<textArray.length;i++){ 
     d3.selectAll(area) //-area you wish to append the text to 
     .append("text") 
     .classed("popUpTextLeft", true) //-CSS class for the text 
     .attr("x", xPos) 
     .attr("y", yPos+(i*20)) //-new line when going through the loop 
     .text(textArray[i]); //-goes through each element in the text array 
    } 
} 

textMultipleRows(popUpTextArray, "#window1", 300,200); 

這是一個有點哈克和它是由D3,所以我不知道如果有很多人會使用它,但正如我所說的它的作品完美的我。

相關問題