Rendering MathJax output on <canvas>

Viewed 3005

I have searched this topic, but not able to find a direct answer, and I am also not good in javascript. So I hope someone can show me how to do this.

I simply like to display math inside canvas2D. I use context.fillText to pass string to canvas2d, but that string is clearly not being processed by Mathjax since it is not on the page itself.

Here is a MWE. What do I need to modify this to make math show up on the canvas?

<!DOCTYPE html>

<html>
<head>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({tex2jax: { inlineMath: [['$','$'],['\\(','\\)']] }});
</script>

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

</p>Trying to render $\sin(x)$ inside canvas 2D as text</p>

<div>
<canvas id="e" width="200" height="200"></canvas>
<script>
  var canvas = document.getElementById("e");
  var context = canvas.getContext("2d");
  context.font = "normal 16px Arial";
  context.fillText("test string", 50, 50);
  context.fillText("$\sin(x)$", 50, 100);
</script>
</div>    
</body>
</html>

The output I get now is

Mathematica graphics

Again, I do understand why it is not working, since the math is inside the string, Mathjax can't see it and process it. But it has to be a string for use by canvas. I can't just write context.fillText($\sin(x)$, 50, 100); without the string quotes, since it will not work.

Might be a related question is this, but not sure.

How do I format html with MathJax after loading it using jQuery.load?

4 Answers

I found a way to put MathJax equations into cavans. Basically, LATEX -> SVG -> base64 -> cavans.

Use MathJax.tex2svg("F=ma") to convert latex to svg element, and then turn it into base64 format, finally put base64 in cavans as image.

This is my code:

var tex = oriData.nodes[i].latex;
var svg = MathJax.tex2svg(tex);
var svg = svg.childNodes[0]
var ssvg = new XMLSerializer().serializeToString(svg);
var base64 = "data:image/svg+xml;base64, " + window.btoa(unescape(encodeURIComponent(ssvg)));

The base64 is the base64 format eqaution SVG data.

Related