My goal is to record maths scripts running on the canvas and at the same time record sound from the mic (I am a math teacher). I would like very much to allow latex formulas. Of course latex formulas do not write directly to canvas. MathJax can produce SVG elements. I wonder if it is possible to go from SVG->image->canvas, using javascript. I don't care if the obtained image on canvas is a little blured. I couldn't find good examples of this yet on the internet. Thanks!
Asked
Active
Viewed 616 times
2 Answers
0
Indeed that's possible. The trick here is to grab the SVG output of MathJax and draw it to a temporary <img>
element, which in-turn is drawn to an on-screen canvas afterwards.
The actual <svg>
element is a children of the <mjx-container>
element returned by a call to MathJax's tex2svg()
method.
Here's an example:
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
let equation = "x = \\sin \\left( \\frac{\\pi}{2} \\right)";
let svg = MathJax.tex2svg(equation).firstElementChild;
let img = document.createElement('img');
img.onload = (e) => {
let tempWidth = e.target.naturalWidth;
let tempHeight = e.target.naturalHeight;
ctx.drawImage(e.target, canvas.width / 2 - tempWidth / 2, canvas.height / 2 - tempHeight / 2, tempWidth, tempHeight)
}
img.src = 'data:image/svg+xml;base64,' + btoa('<?xml version="1.0" encoding="UTF-8" standalone="no" ?>\n' + svg.outerHTML);
#canvas {
background-color: #eeeeee;
}
<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-svg.js" type="text/javascript"></script>
<canvas id="canvas"></canvas>

obscure
- 11,916
- 2
- 17
- 36
-
Thanks, that would help a lot!! – Milton Feb 08 '22 at 11:48