jsMath text metrics

  • mike seeman

    mike seeman - 2008-12-16


    I'm looking at diagramming using the html 5 canvas element.

    In addition I would like to overlay text and annotations, some of
    which will be mathematical.   In order to implement
    accurate positioning of text I need text metric information. 

    Is there some way of getting this from a string in tex format.
    Presumably it would need to
    be parsed/formatted first and then some kind of
    measureText call would give dimensions.  The information
    can be used for accurate placement or collision detection
    of mathematical annotations.

    Any help or pointers on how I might
    do this greatly appreciated.


    • Davide P. Cervone

      The size of the mathematics depends on the CSS settings, and so it is not determined just by the TeX code, but also by the mathematic's placement within the document.  For this reason, jsMath doesn't give you a means of processing a string, but rather processes DOM elements containing math strings.

      So one way to do what you want is to do what you want is to use document.createElement() to create a SPAN (say) and set its innerHTML to the TeX string you want.  Then call jsMath.ProcessElement() on the SPAN element, and finally check the SPAN's offsetHeight and offsetWidth in order to get its size.  This is not a perfect measure, as the DOM size does not always match the TeX box sizes exactly, but may be enough to satisfy your needs.  If you need something more accurate, let me know.

      Note that jsMath.ProcessElement() may run asynchronously, so the element size may not be available immediately after the call completes.  (This can happen if the mathematics requires one of jsMath's extensions to be loaded, for example.)   You should really use jsMath.Synchronize() to make sure that the mathematics is completely typeset before you access its offsetWidth and offsetHeight.  See


      for more details.

      You might also find the discussion at


      to be useful, as it discusses jsMath/canvas issues.



Log in to post a comment.