Text Wrapping

Finding a cleaner way to do text wrapping

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.12.2/d3.js"></script>
<script src="https://d3plus.org/js/d3plus-text.v0.9.full.min.js"></script>
<svg width="1000" height="1000">
</svg>

CSS

body {
  background: #CCC;
}

text {
  text-anchor: middle;
  dominant-baseline: central;
  font-weight: 400;
  font-family: Roboto, sans-serif;
  fill: #fff;
}

foreignObject {
  color: white;
  text-align: middle;
}

JavaScript

const radius = 150;


// Use the d3Plus TextBox class
const d3PlusWrap = (gs, data) => {
	gs.each((d, i, elements) => {
		new d3plus.TextBox()
  						.data([d])
    	        .select(elements[i])
              .fontResize(true)
        	    .height(radius)
          	  .width(radius)
              .text(d => d.name)
              .x(d => -radius / 2)
              .y(d => -radius / 2)
              .ellipsis(text => text.replace(/\.|,$/g, "") + "...")
              .verticalAlign("middle")
              .textAnchor("middle")
            	.render();  
  });
};

const circles = [
 { x: 500, y: 150, name: "ABCDEFGHIJKLMNOPQRSTUVWXYZ1245" },
 { x: 500, y: 500, name: "ABCDEFGHIJKLMNOPQRSTUVWXYZ1" },
];

const join = d3
	.select("svg")
  .selectAll("g")
  .data(circles);
  
const g = join.enter()
							.append("g")
              .attr("transform", d => `translate(${d.x}, ${d.y})`);

g.append("circle")
 .attr("r", radius)
 .style("fill", "#009600");

d3PlusWrap(g, circles);