简体   繁体   中英

SVG node.getBBox incorrect when using @font-face

I have some text that gets rendered using Raphael.text() and with font-family attributes that use fonts loaded using @font-face.

I use OpenType to load the font and render it as base64 and inject that in my stylesheet.

Here's some pseudo code:

// In my css
opentype.load('someFontFamily', (err, font) => {
  // Inject in stylesheets
  const path = paper.text(x, y, 'Hello World')
    .attr({
      'font-family': 'someFontFamily'
      'font-size': 100
    })
  path.getBBox() // Calls path.node.getBBox() in RaphaelJS
}) 

The issue is this. The size, especially the width,as retured by getBBox is not reflective of the font family but instead of some abstract unknown generic font (it's not quite the width of the fallback font so not sure what it is).

The html/page is correctly showing my SVG with the desired font. I can inspect it and the browser sees the correct size.

It's not a question of waiting, I've tried timeouts. It seems that the only way it will work if is the font is preloaded in browser (by having an element on the page using the family and using @font-face in my css which causes a triggering of the font download prior to any SVG rendering.

I've tried adding my fonts as @font-face declarations prior to page loading but it makes no diff.

How can I get SvG to return the size reflecting the font it displays? I suspect it's an internal timing question. It's almost like a need a callback/event for the post render.

Ok. Posting an answer in case it proves useful to some other poor soul.

There are indeed some implementations of the @font-face loading events.

Here's a good article on this.

Cross browser support is still iffy but Font Face Observer looks like a promising library:

Also of interest is:

Some browsers natively support these events. After rendering my text I can call:

document.fonts.load('70px someFontFamily')
  .then(function() {
    console.log(path.node.getBBox())
  })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM