Search code examples
svgd3.jsmathml

Rendering MathML on svg using d3.js


I am trying to render MathML equations on svg using d3.js. Can anyone help me getting a quadratic equation on svg. I tried doing it using foreign object with no success.


Solution

  • I spent quite some time trying to make it work in a JSFiddle with no success, but it works great on my PC. JSFiddle here. Do you mind trying the following and let me know if it works with you too?

    Step 1. Load MathJax

    <script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
    

    Step 2. Use this code to append a foreignObject

    var svg = d3.select("body").append("svg").attr("width",400).attr("height",400)
    var text = svg.append("foreignObject").attr("width",100).attr("height",100)
    text.text("$$ x = \\sum_{i \\in A} i^{2} $$")
    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
    

    However, if you still prefer MathML, then you can use the following:

    text.html("<math display=\"block\"><mrow><mi>x</mi><mo>=</mo><mfrac><mrow><mo>−</mo><mi>b</mi><mo>±</mo><msqrt><mrow><msup><mi>b</mi><mn>2</mn></msup><mo>−</mo><mn>4</mn><mi>a</mi><mi>c</mi></mrow></msqrt></mrow><mrow><mn>2</mn><mi>a</mi></mrow></mfrac></mrow></math>")
    

    I know I am adding more scripts for you to load, but my understanding is that MathML is not really much used any more.

    I hope it helps.

    EDIT Finally a JSFiddle here: link

    Thanks