2012-06-13 53 views
13

我想寫我創建一個矩形內文如下:文本符合SVG元素(使用D3/JS)

body = d3.select('body') 

svg = body.append('svg').attr('height', 600).attr('width', 200) 

     rect = svg.append('rect').transition().duration(500).attr('width', 150) 
         .attr('height', 100) 
         .attr('x', 40) 
         .attr('y', 100) 
         .style('fill', 'white') 
         .attr('stroke', 'black') 

     text = svg.append('text').text('This is some information about whatever') 
         .attr('x', 50) 
         .attr('y', 150) 
         .attr('fill', 'black')​ 

然而,正如你所看到的(http://jsfiddle.net/Tmj7g/3/)的文本被切斷。任何漂亮的方法來創建一個段落內的svg矩形?謝謝,

回答

16

this question的答案可能是相關的。 SVG不提供自動打包文本的方式,但是您可以將HTML嵌入到SVG中,然後使用div爲例。

我已經更新了jsfiddle here,但它不能和動畫一起工作。如果您想使其正常工作並像其他任何SVG元素一樣工作,則必須預先計算換行符並手動插入它們。

+0

是否在IE9這項工作?如果有,還有什麼選擇?我知道這是很久以前的答案。 – Jose

+0

我還沒有在IE9中試過這個。 –

+0

是的,它在IE9中完全不起作用,因爲它不支持外部對象。在D3.js中是否有替代文字的方式? – Jose

15

爲了使它與動畫一起工作,只需將其放入一個組元素中,然後對其進行動畫處理即可。 http://jsfiddle.net/MJJEc/

body = d3.select('body') 
svg = body.append('svg') 
        .attr('height', 600) 
        .attr('width', 200); 
    var g = svg.append('g').attr("transform" ,"scale(0)"); 
    rect = g.append('rect') 
        .attr('width', 150) 
        .attr('height', 100) 
        .attr('x', 40) 
        .attr('y', 100) 
        .style('fill', 'none') 
        .attr('stroke', 'black') 
    text = g.append('foreignObject') 
        .attr('x', 50) 
        .attr('y', 130) 
        .attr('width', 150) 
        .attr('height', 100) 
        .append("xhtml:body") 
        .html('<div style="width: 150px;">This is some information about whatever</div>') 

    g.transition().duration(500).attr("transform" ,"scale(1)"); 
3

這種技術可能會派上用場。 它的工作原理與目前的SVG規範,不foreignObject元素 http://bl.ocks.org/mbostock/7555321

+0

雖然這個鏈接可能回答這個問題,但最好在這裏包含答案的基本部分,並提供參考鏈接。如果鏈接頁面更改,則僅鏈接答案可能會失效 – Ian

2

我也有類似的問題,並通過計算我的框的寬度找到合理的解決方案。 其次,我發現平均而言,我當前字體的字符寬度大約爲8. 接下來,我只是在要顯示的文本上做一個子字符串。 這似乎在大多數情況下完美工作。

var rectText = rectangles.append("text") 
    .text(function(d) { 

     TextBoxLength = timeScale(dateFormat.parse(d.endTime)) - timeScale(dateFormat.parse(d.startTime)); 
     return d.task.substring(0, Math.floor(TextBoxLength/8)); 
    }) 
    .attr("x", function(d) { 
     return (timeScale(dateFormat.parse(d.endTime)) - timeScale(dateFormat.parse(d.startTime)))/2 + timeScale(dateFormat.parse(d.startTime)) + theSidePad; 
    }) 
    .attr("y", function(d, i) { 
     return d.position * theGap + 14 + theTopPad; 
    }) 
    .attr("font-size", 12) 
    .attr("text-anchor", "middle") 
    .attr("text-height", theBarHeight) 
    .attr("fill", "#000000"); 
2

另一種方法,試圖將文本的直線爲SVG元素時,可以使用在http://bl.ocks.org/mbostock/1846692發現策略:

node.append("text") 
    .text(function(d) { return d.name; }) 
    .style("font-size", function(d) { return Math.min(2 * d.r, (2 * d.r - 8)/this.getComputedTextLength() * 24) + "px"; }) 
    .attr("dy", ".35em");