关于javascript:如何在svg rect中打包文本

How to pack text inside svg rect

我希望将svg文本放入rect中。我可以使用一种方法来比较宽度并为文本添加换行符,但这并不繁琐。

有没有比这更优雅的方法了?也许通过使用CSS或d3?

更新:以下代码使用d3附加foreignObject,但不显示div。 (在代码检查器中)

1
2
3
var group = d3.select("#package");
var fo = group.append("foreignObject").attr("x", 15).attr("y", 15).attr("width", 190).attr("height", 90);
fo.append("div").attr("xmlns","http://www.w3.org/1999/xhtml").attr("style","width:190px; height:90px; overflow-y:auto").text("Thiggfis the dgdexsgsggs wish to fit insidegssgsgs");
1
2
3
4
5
6
7
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js">

<p id="p"></p>

<svg width="220" height="120" viewBox="0 0 220 120" id="package">
    <rect x="10" y="10" width="200" height="100" fill="none" stroke="black"/>
</svg>


不能通过attr分配名称空间,这是元素创建的副作用。您需要一个html div,因此您需要通过调用元素xhtml:div来告诉d3,一旦执行此操作,其余的操作将由d3完成。

1
2
3
var group = d3.select("#package");
var fo = group.append("foreignObject").attr("x", 15).attr("y", 15).attr("width", 190).attr("height", 90);
fo.append("xhtml:div").attr("style","width:190px; height:90px; overflow-y:auto").text("Thiggfis the dgdexsgsggs wish to fit insidegssgsgs");

1
2
3
4
5
6
7
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js">

<p id="p"></p>

<svg width="220" height="120" viewBox="0 0 220 120" id="package">
    <rect x="10" y="10" width="200" height="100" fill="none" stroke="black"/>
</svg>


这是foreignObject的简单示例,用于将HTML标记插入SVG:

1
2
3
4
5
6
<svg width="220" height="120" viewBox="0 0 220 120">
  <rect x="10" y="10" width="200" height="100" fill="none" stroke="black" />
  <foreignObject x="15" y="15" width="190" height="90">
    This is the text I wish to fit inside <wyn>rect</wyn>
  </foreignObject>
</svg>