S.Dan
S.Dan

Reputation: 1902

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>

Upvotes: 4

Views: 4843

Answers (2)

Robert Longson
Robert Longson

Reputation: 123985

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>

Upvotes: 5

r3mainer
r3mainer

Reputation: 24547

Here's a simple example of a foreignObject used to insert HTML markup into an SVG:

<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>

Upvotes: 3

Related Questions