Share this blog!

How to pack text inside svg rectangle

SVG or scalabale vector graphics are used to define graphics for the web in XML format. SVG is a W3C recommendation and integrates with W3C standards such as DOM and XSL.

Since SVG components are treated as graphics, the display attributes of the elements are based on the position vector and other attributes such as width, height, fill etc. Even a text element is treated the same way.

In html components, if you have the requirement to pack text inside a rectangle, you can simply define a <div> with text and apply a border to the <div>. It’s because div’s are allowed to have child components.

In SVG however, if you want to bind a rectangle with text, this scenario is a bit different because most of the components are not allowed to have inner or child elements. However, you are allowed to use <g> to group elements.

The best method to add the text inside a rectangle is to use a foreign object with similar dimensions of the rectangle and using CSS to control overflow. The following demonstrates a text being bounded by a rectangle’s boundaries.

<svg width="220" height="120" viewBox="0 0 220 120"> 
   <g id=”my-group”> 
   <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> 
   </g> 
</svg> 

If d3 is involved:

The above result can be obtained using d3’s append. However, steps should be taken to assign the namespace correctly, especially for appending div.

var svg = d3.select(“svg”); 
var group = svg.append(“g”).attr(“id”,”my-group”); 
var rectangle = group.append(“rect”).attr(“x”,10…….. 
var fo = group.append(“foreignObject”).attr(“x”,10……. 
var div= fo.append(“xhtml:div”).attr(“style”,…).text(“text...
Next PostNewer Post Previous PostOlder Post Home

0 comments:

Post a Comment