Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pack text inside svg rect

I wish to fit svg text inside a rect. I could use an approach to compare the widths and add line breaks to the text, but it's not tedious.

Is there a more elegant way than this? Maybe by using CSS or d3?

UPDATE:the following code appends foreignObject using d3 but the div is not displayed. (it is there in the code inspecter)

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>
like image 222
S.Dan Avatar asked Feb 06 '23 23:02

S.Dan


1 Answers

A namespace cannot be assigned by attr, it's a side effect of element creation. You need an html div so you need to tell d3 that by calling the element xhtml:div, once you do that, d3 will do the rest.

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>
like image 138
Robert Longson Avatar answered Feb 08 '23 17:02

Robert Longson