Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SVG foreignObject doesn't display in Safari

I'm using d3 with svg:foreignObject to create a formatted text box that appears next to a data point on hover. The below strategy works perfectly in Chrome, but the foreignObject is not visible in Safari. The Safari inspector shows the foreignObject in the DOM, in the proper location and with all the correct data. I just can't see it! What am I missing?

My code looks like this:

var description = svg.append('foreignObject')
  .attr('class', 'description')
  .attr('id', 'desc')
  .attr('x', x)
  .attr('y', y)
  .attr('width', width);

var descdiv = description.append('xhtml:div')
  .append('div')
  .attr('id', 'textBox');

descdiv.append('p')
  .attr('class', 'text1')
  .attr('dy', '1em')
  .html('First line');

descdiv.append('p')
  .attr('class', 'text2')
  .attr('dy', '2em')
  .html('<tspan class="text3">' + 'Second line 1st part + '</tspan><tspan class="text4">' + ', ' + 'Second line 2nd part' + '</tspan>');

descdiv.append('p')
  .attr('class', 'text1')
  .attr('dy', '3em')
  .html('Third line');

EDIT
It turns out the issue is that foreignObject requires a height attribute in order to display in Safari (but not in Chrome, interestingly). I can set the height after the above, like so:

d3.select('#desc').attr('height', height);

But the problem now is getting the height of the text box that has no height attribute (because the height needs to vary with the length of the text). I think something like getComputedTextLength might work, but I can't quite figure it out. Any suggestions greatly appreciated.

like image 704
user6647072 Avatar asked Nov 09 '22 11:11

user6647072


1 Answers

you should set height and width property to foriegnObject.

var description = svg.append('foreignObject')
  .attr('class', 'description')
  .attr('id', 'desc')
  .attr('x', x)
  .attr('y', y)
  .attr('width', width)
  .attr('height', xxx);
like image 97
peng Avatar answered Nov 14 '22 22:11

peng