Is it possible to justify SVG text using d3js?

325 views Asked by At

I'm wrapping text using M.Bostock's wrap function but can't find a way to justify it.

Is that even possible in d3 ? If not, is there a way to "mimic" this kind of text disposition ?

EDIT: Thanks to Logikos suggestion, i've found this example from M.Bostock putting a foreignObject inside svg.

Here is the snippet:

var svg = d3.select("body").append("svg")
    .attr("width", 960)
    .attr("height", 500);
svg.append("foreignObject")
    .attr("width", 480)
    .attr("height", 500)
  .append("xhtml:body")
    .style("font", "14px 'Helvetica Neue'")
    .html("<h1>An HTML Foreign Object in SVG</h1><p>Veeery long text");

Then you just need to add in the CSS:

body {text-align: justify;
     text-align-last: start;
} 
1

There are 1 answers

1
tempcke On BEST ANSWER

It is not exactly what your looking for but something I used several years ago. Instead of using that function to mimic wrapping you can instead put html inside svg with the foreignObject tag - http://ajaxian.com/archives/foreignobject-hey-youve-got-html-in-my-svg

As html you can style it however you want, text wrapping, justified etc etc.

I have not worked with d3 or SVG's in over 5 years so it is difficult to remember but thought I'd share this in-case it was of any use.

This is the example markup from the link I posted above:

< ?xml version="1.0" standalone="yes"?>
<svg xmlns = "http://www.w3.org/2000/svg">
  <rect x="10" y="10" width="100" height="150" fill="gray"/>
  <foreignobject x="10" y="10" width="100" height="150">
    <body xmlns="http://www.w3.org/1999/xhtml">
      <div>Here is a <strong>paragraph</strong> that requires <em>word wrap</em></div>
    </body>

  </foreignobject>

  <circle cx="200" cy="200" r="100" fill="blue" stoke="red"/>
  <foreignobject x="120" y="120" width="180" height="180">
    <body xmlns="http://www.w3.org/1999/xhtml">
      <div>
        <ul>
          <li><strong>First</strong> item</li>

          <li><em>Second</em> item</li>
          <li>Thrid item</li>
        </ul>
      </div>
    </body>
  </foreignobject>
</svg>

Please note browser support: http://caniuse.com/#search=foreignObject Which says it will work in everything other than opera mini. Though there are some limitations in IE and Edge:

1 IE11 and below do not support . 2 IE and Edge do not support applying SVG filter effects to HTML elements using CSS.

You should check it in IE and Edge, in one place the site says it does not support it, in another it says it supports it somewhat...