getBBox() shows previous bbox?

How do I get bbox to always return the proper dimensions?

  1. Open Font getBBox / Martien van Steenbergen | Observable
    • has font PT Sans Narrow selected;
    • shows a red outline around the text; its bounding box;
  2. Select font Roboto Slab:
    • rerenders the text in the new font;
    • shows a bbox that is shorter than the text: text now extends beyond the bbox;
  3. Switching between fonts while keeping everything else the same shows a wrong bbox most of the time.
  4. Change the font size or the text:
    • bbox now shows proper sizes.

Guess: it may have something to do with the time it needs to load fonts. I have tried several approaches but failed.

Your notebook appears to be private?

Sorry. It was and is Public. Probably the colon at the end of the url. It fooled me too. I removed it. Can you try again please?

You can probably use the Font Loading API to wait for the fonts to get loaded. You may need to ensure that your style element has been added to the DOM before awaiting the font’s loaded promise.

This should give you an overview of what you’re working with:

[...document.fonts].map(f => Object.fromEntries(
  Object.keys(f.constructor.prototype).map(k => [k, f[k]])
))

Thanks. Will do. Now investigating…

Fixed it using Web Font Loader: Text Bounding Box / Martien van Steenbergen | Observable

Improvements and questions welcome!

Thanks for your exposeProps above.

TIL You can conveniently observe and test this behaviour when you emulate slow network connections using Chrome – e.g. by setting network throttling to Fast 3G en switch between fonts or change font size or weight.

I always add custom profile “Almost offline” with Download speed set to 1:

1 Like