3

I would like to be able to write formulas in latex in a fabric.js canvas, perhaps with MathJax.

http://fabricjs.com/fabric-intro-part-2#text

Is it possible to do that?

user1506145
  • 5,176
  • 11
  • 46
  • 75

1 Answers1

6

I would use the SVG renderer of MathJax to create a SVG file and then load that SVG into fabric.js. Here's an example:

<!-- It is important to use the SVG configuration of MathJax! -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-AMS-MML_SVG">
</script>

<!-- You might need at least Fabric 1.4.6, because of a bug with data URLs -->
<script type="text/javascript" src="https://raw.githubusercontent.com/kangax/fabric.js/master/dist/fabric.js">
</script>

<body>
  <canvas id="canvas" width="400" height="400"></canvas>

  <script type="text/javascript">
    // This function does the actual work
    function tex(text, callback) {
        // Create a script element with the LaTeX code
        var div = document.createElement("div");
        div.style.position = "absolute";
        div.style.left = "-1000px";
        document.body.appendChild(div);
        var se = document.createElement("script");
        se.setAttribute("type", "math/tex");
        se.innerHTML = text;
        div.appendChild(se);
        MathJax.Hub.Process(se, function() {
            // When processing is done, remove from the DOM
            // Wait some time before doing tht because MathJax calls this function before
            // actually displaying the output
            var display = function() {
                // Get the frame where the current Math is displayed
                var frame = document.getElementById(se.id + "-Frame");
                if(!frame) {
                    setTimeout(display, 500);
                    return;
                }

                // Load the SVG
                var svg = frame.getElementsByTagName("svg")[0];
                svg.setAttribute("xmlns", "http://www.w3.org/2000/svg");
                svg.setAttribute("version", "1.1");
                var height = svg.parentNode.offsetHeight;
                var width = svg.parentNode.offsetWidth;
                svg.setAttribute("height", height);
                svg.setAttribute("width", width);
                svg.removeAttribute("style");

                // Embed the global MathJAX elements to it
                var mathJaxGlobal = document.getElementById("MathJax_SVG_glyphs");
                svg.appendChild(mathJaxGlobal.cloneNode(true));

                // Create a data URL
                var svgSource = '<?xml version="1.0" encoding="UTF-8"?>' + "\n" + '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">' + "\n" + svg.outerHTML;
                var retval = "data:image/svg+xml;base64," + btoa(unescape(encodeURIComponent(svgSource)));


                // Remove the temporary elements
                document.body.removeChild(div);

                // Invoke the user callback
                callback(retval, width, height);
            };
            setTimeout(display, 1000);
        });
    }


    document.onload = function() {
      var canvas = new fabric.Canvas("canvas");

      tex("1+\\int_x^y e^x dx + \\ldots", function(svg, width, height) {
          // Here you have a data url for a svg file
          // Draw using FabricJS:
          fabric.Image.fromURL(svg, function(img) {
              img.height = height;
              img.width = width;
              canvas.add(img);
          });
      });
    };
  </script>
</body>

I've also put that into a JsFiddle: http://jsfiddle.net/3aHQc/39/

Phillip
  • 13,448
  • 29
  • 41
  • I had only tested the code in Firefox 29. Apparently Chrome (or whichever else you're using) does not support the `outerHTML` property for svg images yet. I've updated the example to also work with other browsers. – Phillip Jun 03 '14 at 08:09
  • FYI: Github user asturur recently [added support for loading the SVG through `loadSVGFromString`](https://github.com/kangax/fabric.js/issues/1373). Using this function instead of `Image.fromURL` should improve scaling quality in Firefox. – Phillip Jun 30 '14 at 06:46
  • Thanks for your answer, I also see that it is an image so it's not rescaled. How do I use loadSVGFromString, just swap it for the Image.fromUrl? Would you like to send a fiddle? :) – user1506145 Jul 16 '14 at 13:10
  • There are some examples here on SO, e.g. [here](http://stackoverflow.com/questions/13192798/distorted-result-with-fabric-loadsvgfromstring), for how to use the function. To get the SVG as a string, make the loader function invoke `callback` using `svgSource` instead of `retval` as an argument. – Phillip Jul 16 '14 at 19:18
  • 1
    Note from the future: cdn.mathjax.org is nearing its end-of-life, check https://www.mathjax.org/cdn-shutting-down/ for migration tips. – Peter Krautzberger Apr 12 '17 at 09:07
  • why does the function return an error TypeError: svg is undefined :x – flex_ Mar 06 '18 at 20:50