getting width of element created by `tex2svg`

Hey folks…

So I like to put nicely formated math in my svgs using MathJax’s tex2svg, following the fantastic guidance from @mcmcclur such as here: SVG and MathJax 3 / Mark McClure | Observable.

I’m wanting to get more precise about how I position the elements created by tex2svg. For this purpose, I’d like to be able to get the width and height of any bit of math inserted by tex2svg.

I’ve been banging my head against this for a couple of hours, and haven’t been able to find a solution. My approach has been to try to use d3’s getBBox(). But that function returns 0 width and 0 height when applied to all the elements produced when I use tex2svg. Here’s a notebook demonstrating my failed attempts:

Note that you’ll need to use developer tools to see the failures that notebook generates. Each cell does a console.log() to show what’s returned from getBBox().

Help?

Thank you!

1 Like

getBBox only works correctly after the element is laid out on the webpage. So, try the following:

First, give your output SVG a name to reference - perhaps, something like svg_with_math.

Then, in a new cell, try the following:

d3
  .select(svg_with_math)
  .selectAll("g.math")
  .nodes()
  .map(function (svg_element) {
    let rect = svg_element.getBBox();
    return { width: rect.width, height: rect.height };
  })

I get the following when I do that:

[
  {width:8.887125968933105, height:8.266669273376465},
  {width:139.96884155273438, height:17.62497329711914},
  {width:52.637535095214844, height:46.82771301269531}
]

Often, this means you need to render an SVG and then modify it to get more precisely what you want. In practice, that’s not noticeable to the user.

2 Likes