使用mathjax或类似方法将Latex/MathML转换为SVG或Image?

Onz*_*nza 5 javascript svg mathjax

我正在构建一个只允许对象渲染功能的库来返回自己表示的DOM元素,其中一个是数学,所以<img>,<canvas>或者<svg>会这样做,我更喜欢svg.

Mathjax因此非常擅长而闻名,但我需要更多的东西:

Mathjax.Latex('\frac{2}{1}').toSVG(); //svg DOM node or string
Mathjax.Latex('\frac{2}{1}').toImage(); //Image, img node, or base64
Run Code Online (Sandbox Code Playgroud)

我知道有可能使用mathjax-node,但是它是否与mathjax客户端有关?https://github.com/mathjax/MathJax-node

Pet*_*ger 10

没有内置的方法.但你显然可以建立一些东西.

这是一个快速而肮脏的例子.请注意,此示例将MathJax配置为不将其globalCache用于SVG路径; 这使得SVG输出易于重复使用.渲染分离的DOM节点也有一些注意事项; MathJax必须猜测上下文(CSS,字体指标等).

window.MathJax = {
  jax: ["input/TeX", "output/SVG"],
  extensions: ["tex2jax.js", "MathMenu.js", "MathZoom.js"],
  showMathMenu: false,
  showProcessingMessages: false,
  messageStyle: "none",
  SVG: {
    useGlobalCache: false
  },
  TeX: {
    extensions: ["AMSmath.js", "AMSsymbols.js", "autoload-all.js"]
  },
  AuthorInit: function() {
    MathJax.Hub.Register.StartupHook("End", function() {
      var mj2img = function(texstring, callback) {
        var input = texstring;
        var wrapper = document.createElement("div");
        wrapper.innerHTML = input;
        var output = { svg: "", img: ""};
        MathJax.Hub.Queue(["Typeset", MathJax.Hub, wrapper]);
        MathJax.Hub.Queue(function() {
          var mjOut = wrapper.getElementsByTagName("svg")[0];
          mjOut.setAttribute("xmlns", "http://www.w3.org/2000/svg");
          // thanks, https://spin.atomicobject.com/2014/01/21/convert-svg-to-png/
          output.svg = mjOut.outerHTML;
          var image = new Image();
          image.src = 'data:image/svg+xml;base64,' + window.btoa(unescape(encodeURIComponent(output.svg)));
          image.onload = function() {
            var canvas = document.createElement('canvas');
            canvas.width = image.width;
            canvas.height = image.height;
            var context = canvas.getContext('2d');
            context.drawImage(image, 0, 0);
            output.img = canvas.toDataURL('image/png');
            callback(output);
          };
        });
      }
      mj2img("\\[f: X \\to Y\\]", function(output){
        document.getElementById("target").innerText = output.img + '\n' + output.svg;
      });
    });
  }
};

(function(d, script) {
  script = d.createElement('script');
  script.type = 'text/javascript';
  script.async = true;
  script.onload = function() {
    // remote script has loaded
  };
  script.src = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js';
  d.getElementsByTagName('head')[0].appendChild(script);
}(document));
Run Code Online (Sandbox Code Playgroud)
<div id="target"></div>
Run Code Online (Sandbox Code Playgroud)