繁体   English   中英

如何在svg rect中打包文本

[英]How to pack text inside svg rect

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

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

更新:以下代码使用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无法分配命名空间,这是元素创建的副作用。 你需要一个html div,所以你需要告诉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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM