MathJax inside SVG

前端 未结 3 1430
春和景丽
春和景丽 2021-02-03 23:59

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

3条回答
  •  借酒劲吻你
    2021-02-04 00:15

    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.

提交回复
热议问题