如何在svg rect内打包文本

How to pack text inside svg rect

本文关键字:包文本 文本 svg rect      更新时间:2023-09-26

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

还有比这更优雅的方式吗?也许通过使用CSS或d3?

UPDATE:下面的代码使用d3追加了foreignObject,但是div不显示。(它在代码检查器中)

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");
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<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分配,这是元素创建的副作用。你需要一个htmldiv,所以你需要告诉d3,通过调用元素xhtml:div,一旦你这样做,d3会做剩下的。

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");
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<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>

下面是一个用于将HTML标记插入SVG的foreignObject的简单示例:

<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">
    <div xmlns="http://www.w3.org/1999/xhtml" style="width:190px; height:90px; overflow-y:auto"><b>This</b> is the <i>text</i> I wish to fit inside <code>rect</code></div>
  </foreignObject>
</svg>