Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to set max-width of SVG text

Tags:

I have an extremely simple page and task but to my dismay I can't get my text to take on the proper max-width. I have looked at : read width of d3 text element, Whats the CSS to make something go to the next line in the page?, among others, but I still can't figure it out.

Instead of the svg text flowing nicely to the next line, it sprawls out across the page until it runs out of bounds. Here is my css and code

var svg = d3.select('body').append('svg')
    .attr('width', 300)
    .attr('height', 200);

var textG = svg.append('g');

textG.append('text')
    .attr('x', 20)
    .attr('y', 30)
    .attr('class', 'myText')
    .text('This line should be about three to four lines long, but because I am so stupid I cannot make it do what I want it to do. Woe is me.');
.myText {
    font-size: 1.3em;
    fill: gray;
    width:10%;
    max-width:10%;
    display:block;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="//d3js.org/d3.v3.min.js"></script>
</head>
<body>

Question: What can I do from the CSS side or the JS side to make my svg text take on a max width style rule? I want it to go to the next line instead of infinitely marching on in the confines of the first line.

like image 651
Arash Howaida Avatar asked Jun 01 '18 06:06

Arash Howaida


1 Answers

What you can do is split your string into three or four parts and then use multiple <tspan> elements in a <text> element instead of inserting the whole text into the <text>.

Another solution is to use a <foreignObject>.

Here's a fiddle:

var svg = d3.select('body').append('svg')
  .attr('width', 350)
  .attr('height', 500);

var textG = svg.append('g');

var fullTxt = 'This line should be about three to four^lines long, but because I am still^learning stuff, I cannot make it do^what I want it to do. Woe is me.'

var b = fullTxt.split('^');

textG.append('text')
  .attr('x', 20)
  .attr('y', 30)
  .attr('class', 'myText')
  .selectAll('tspan').data(b)
  .enter().append('tspan')
  .text(function(d) {
    return d;
  })
  .attr("textLength", 250)
  .attr("lengthAdjust", "spacingAndGlyphs")
  .attr('dy', '1em').attr('x', '15');
.myText {
  font-size: 1.3em;
  fill: gray;
  width: 10%;
  max-width: 10%;
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <script src="//d3js.org/d3.v3.min.js"></script>
</head>

<body>
like image 178
Aditya Avatar answered Oct 24 '22 23:10

Aditya