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 occasi
I've used the following, which defines a function that takes latex code as input and appends the MathJax processed svg to a target SVG element.
// First create a new element to hold the initial Latex code
// and eventual MathJax generated SVG. This element isn't added
// to the main docuemnt, so it's never seen.
let mathBuffer = document.createElement("div");
// Then define a function that takes LaTeX source code
// and places the resulting generated SVG in a target SVG element.
mathSVG = function (latex, target) {
// Update the buffer with the source latex.
mathBuffer.textContent = latex;
// Get MathJax to process and typeset.
MathJax.Hub.Queue(["Typeset", MathJax.Hub, mathBuffer]);
// Queue a callback function that will execute once it's finished typesetting.
MathJax.Hub.Queue(function () {
// This (svg) is the generated graphics.
const svg = mathBuffer.childNodes[1].childNodes[0];
// The next line is optional, play with positioning as you see fit.
svg.setAttribute("y", "-11pt");
// Move the generated svg from the buffer to the target element.
target.appendChild(svg);
// Clear the buffer.
mathBuffer.textContent = "";
});
};
In the above, I'm assuming an html host document with svg elements within. It should also work in a svg host document too.