Is there a way to measure text?

hi,

if I have a string, can I measure it using goJS without rendering a TextBlock?

using a hidden html element for this seems to be getting slightly different results than a rendered text block… so that’s not an option.

thanks,
cAndrei

If you want to get the dimensions of some text in the same manner that a TextBlock does, respecting wrapping and multiple lines and special characters and fonts and all that, you’ll need to use a TextBlock.

For the simplest cases, though, you might be able to call CanvasRenderingContext2D.measureText() - Web APIs | MDN.

ok… makes sense…

then… next question:
is it possible to create a TextBlock and measure it without actually making it visible on the diagram?

Yes. Here’s one way:

  var myGlobalPart =
    $(go.Part,
      $(go.TextBlock));

  function measure() {
    var str = "hello there! " + Math.random() * 1000000;
    myGlobalPart.elt(0).text = str;
    myGlobalPart.ensureBounds();
    console.log("size of '" + str + "' is: " + myGlobalPart.elt(0).naturalBounds.size.toString());
  }

produces on my machine in Firefox:

size of 'hello there! 149436.73362242704' is: Size(190,14.3)
size of 'hello there! 75044.07500542553' is: Size(183,14.3)
size of 'hello there! 47944.67350051201' is: Size(183,14.3)
size of 'hello there! 844972.214625441' is: Size(176,14.3)

thank you… that works perfectly! :)