In my current scenario, I am looking to add short to medium snippets of text in various parts of my visualization. However, the default behavior results in unattractive output as SVG text is simply appended all at once. After some research, I came across a clever method by Mike Bostock to handle longer strings in SVG text, which can be found here. I attempted to adapt this technique to my specific visualization, but it didn't yield the desired outcome. Here's the code snippet:
var margins = {top:20, left:50, bottom:100, right:20};
var width = 1200;
var height = 500;
var totalWidth = width+margins.left+margins.right;
var totalHeight = height+margins.top+margins.bottom;
var svg = d3.select('body')
.append('svg')
.attr('width', totalWidth)
.attr('height', totalHeight);
var graphGroup = svg.append('g')
.attr('transform', "translate("+margins.left+","+margins.top+")");
// Rest of the JavaScript code...
d3.selectAll('.labelText')
.call(wrap, 120);
text {
font-family: Tw Cen MT;
}
.date {
font-size: 18px;
paint-order: stroke;
stroke: #fff;
stroke-width: 3px;
stroke-linecap: butt;
stroke-linejoin: miter;
font-weight: 800;
}
<script src="https://d3js.org/d3.v5.min.js"></script>
I understand the concept behind it, and I followed the steps outlined by Bostock in the example. However, the text doesn't seem to pass through the function correctly for wrapping to occur, with no errors being reported.
Question
Can we modify Bostock's tspan wrap function to work universally? If so, how can we achieve this if the text isn't selected and the function isn't called with the desired width?
Further Clarifications:
- Font size: 12px
- Desired width: 120
Bonus Points:
- Desired text alignment: Right (Bostock's example features centered text)