在JavaScript中将latex渲染为svg,并使用paper.js显示结果



下面的代码给出了"脚本错误";。非常感谢您的帮助。

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.12.11/paper-full.min.js"></script>
<script>
window.MathJax = {
// options
};
</script>
<script type="text/javascript" id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-svg.js"></script>
<canvas id="canvas_1"></canvas>

javascript

var graphScope = new paper.PaperScope();
var canvas_1 = document.getElementById('canvas_1');
graphScope.setup(canvas_1);
graphScope.activate();
const latexToImg = function(formula) {
return new Promise((resolve, reject) => {
let wrapper = MathJax.tex2svg(`${formula}`, {
em: 10,
ex: 5,
display: true
})
let output = {
svg: "",
img: ""
}
let mjOut = wrapper.getElementsByTagName("svg")[0]
// mjOut.setAttribute("xmlns", "http://www.w3.org/2000/svg")
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');
resolve(output.img)
}
image.onerror = function() {
reject()
}
})
}
const svgGroup = graphScope.project.importSVG(latexToImg('x^2'));

MathJax和Paper.js都直接使用SVG,因此显然不需要创建中间画布元素。此外,MathJax.tex2svg创建了一个SVG DOM元素,Paper.js可以使用该元素(importSVG可以使用SVG字符串、DOM元素或url字符串(。这大大简化了代码,因为它删除了所有画布操作,并且所有操作都是同步的。

但由于某种原因,它的尺寸很小,所以我把它放大了20倍。

var graphScope = new paper.PaperScope();
var canvas_1 = document.getElementById('canvas_1');
graphScope.setup(canvas_1);
graphScope.activate();
const latexToImg = function(formula) {
let wrapper = MathJax.tex2svg(formula, {
em: 10,
ex: 5,
display: true
})
return wrapper.querySelector('svg');
}
const svgGroup = graphScope.project.importSVG(latexToImg('x^2'));
var bounds;
svgGroup.scale(20);
// for automatic scaling, use these lines instead:
// bounds = svgGroup.strokeBounds;
// svgGroup.scale(40 / bounds.height);
bounds = svgGroup.strokeBounds;
svgGroup.position.x = -bounds.x;
svgGroup.position.y = -bounds.y;
<script src="https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.12.11/paper-full.min.js"></script>
<script>
window.MathJax = {
// options
};
</script>
<script type="text/javascript" id="MathJax-script" src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-svg.js"></script>
<canvas id="canvas_1"></canvas>

快速查看您的代码后,我会说:

  1. 您正在向importSVG函数传递一个promise
  2. importSVG函数期望接收一个SVG字符串,您的承诺将通过一个PNG图像数据url来解决

最新更新