0

I'd like to calculate the length of a text with a specific font before drawing it. I found this stackoverflow answer and used it in my code. This could work nice but for this to work I need to draw the text before I draw the box that is supposed to contain the text as a label.

This is my test code which gets the length of the text and is supposed to use it for the box width:

// Draw Label first so we get the min width for the box
if (this.label) {
    var text = draw.plain(this.label)
    text.move(this.x + 5, this.y + 5);
    text.font(cfgText);
    var length = document.getElementsByTagName('text')[0].getComputedTextLength());
}

// Draw underlying box
var rect = draw.rect(this.width, this.height);
rect.move(this.x, this.y);
rect.fill(pink);
rect.mouseover(shift);

Is there a way to calculate the length of the text correctly? I'd like to stay in the SVG.js context if possible.

I think this problem would be solved by either calculating the text length beforehand or drawing the text first, getting its length and then pulling it back into the foreground.

Any ideas?

Community
  • 1
  • 1
FabianTe
  • 516
  • 4
  • 22

0 Answers0