I'm doing some writing where I use MathJax to render the math. I also occasionally include SVG diagrams which are generated dynamically by javascript. Those SVG diagrams occasionally include math.
I'd like the text elements in those SVG diagrams to be rendered using MathJax. I know how to cause the dynamic math to be rendered. However, the mathjax output is in <span>
s which aren't valid SVG and don't show up.
This persists when I configure MathJax to use SVG output mode, though this is perhaps due to an improper use of SVG output mode. I changed by MathJax CDN link to http://cdn.mathjax.org/mathjax/2.1-latest/MathJax.js?config=TeX-AMS-MML_SVG
, which did not produce SVG output. I haven't been able to coax MathJax into actually outputting SVG elements yet.
I've considered using an SVG <foreignObject>
tag which is non-ideal because (to my knowledge) I must specify a width and height, which is inconvenient.
Is there a better way to include MathJax rendered text inside SVG inside HTML?
Currently, the only way to include MathJax within an SVG diagram is through <foreignObject>
. Yes, it is not ideal, not only because you need to provide a size, but also because IE9+ doesn't support <foreignObject>
.
As for the SVG output, if you have used the MathJax contextual menu to select a math render, that will override the renderer choice in the document, so you may still be seeing HTML-CSS output for that reason. The value is stored in a cookie, so that it will be remembered from session to session. You can delete the cookie to remove the setting, or use the MathJax menu again to select SVG rendering.
Note, however, that this isn't going to help you either, as MathJax's SVG output is not just an SVG snippet that can be included into a larger SVG file, but include some HTML and the <svg>
element itself. Moreover, MathJax needs the surrounding HTML to determine things like the font-size to use, and some other factors, so it is not going to be able to placed directly into your SVG diagram.
The <foreignObject>
approach is really the only reliable way at the moment.
Edit: Here is a full example:
<!DOCTYPE html>
<html>
<head>
<title>MathJax in SVG diagram</title>
<script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_SVG"></script>
</head>
<body>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="1000" height="500">
<circle cx="100" cy="100" r="99" fill="yellow" stroke="red" />
<circle cx="100" cy="100" r="3" fill="blue" />
<foreignObject x="100" y="100" width="100" height="100">
<div xmlns="http://www.w3.org/1999/xhtml" style="font-family:Times; font-size:15px">
\(\displaystyle{x+1\over y-1}\)
</div>
</foreignObject>
</svg>
</body>
</html>