使文本适合SVG元素(使用D3/JS)

mik*_*ike 13 javascript svg text 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')?
Run Code Online (Sandbox Code Playgroud)

但是,正如您所见(http://jsfiddle.net/Tmj7g/3/),文本被切断了.创建svg矩形内部的段落的任何好方法?谢谢,

Lar*_*off 16

这个问题的答案可能是相关的.SVG无法自动包装文本,但您可以在SVG中嵌入HTML,然后使用div例如.

我在这里更新了jsfiddle ,但它与动画一起使用效果不佳.如果要使其正常工作并且行为与任何其他SVG元素一样,则必须预先计算换行符并手动插入它们.


Gus*_*Ost 14

要使其与动画一起使用,只需将其包含在组元素中,然后为该元素设置动画. 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)");
Run Code Online (Sandbox Code Playgroud)