1

I'm using the answer of this question (Calculate text width with JavaScript), creating a div hidden and calculating the string size. Then, I create a svg rect with the same width of the string + 10.

tipnode.append("rect")
  .attr("height", 25)
  .attr("x", function(d){return d.x*180+45 - getTextWidth(testsize(d.name))/2.0;})
  .attr("y", function(d) { return (d.y-1)*80+45; })
  .attr("width", function(d){return getTextWidth(testsize(d.name))+10;});

getTextWidth function as follows

 function getTextWidth(text) {
  var test = document.getElementById("Test");
  test.innerHTML = text;
  var width = test.clientWidth;
  return width;
  };

Function testsize is just to resize big strings.

Test css:

#Test{
  font-family: 'Alegreya Sans SC', sans-serif;
  font-size: 10.5px;
  font-weight: bold;
  position: absolute;
  visibility: hidden;
  height: auto;
  width: auto;
  white-space: nowrap;
}

The font configuration is the same as the text on rect. Alegreya Sans SC is a font (https://fonts.google.com/specimen/Alegreya+Sans+SC).

The problem is: Sometimes, when I load the page, the rect gets bigger that the text. Then, I change the line "var width = test.clientWidth;" to "var width = test.clientHeight;", load the page, put the original code back, reload the page and the rects width fits exactly! The same code is getting different results!

Please help, I don't know what to do anymore :(

Community
  • 1
  • 1

0 Answers0