1、前言
最近公司的一个项目需求是在前端显示Latex转化的数学公式,经过不断的百度和测试已基本实现。现在此做一个记录。
2、MathJax介绍
MathJax是一款运行在浏览器中的开源的数学符号渲染引擎,使用MathJax可以方便的在浏览器中显示数学公式,不需要使用图片。目前,MathJax可以解析Latex、MathML和ASCIIMathML的标记语言。(Wiki)
3、步骤
3.1、引入MathJax
在使用MathJax之前,需要通过CDN引入, 在<body>
标签中添加,该语句导入的是国内的CDN。vue项目则放在index.ejs下
<link rel="dns-prefetch" href="//cdn.mathjax.org" /> //引入速度更快
<script type="text/javascript" src="http://cdn.bootcss.com/mathjax/2.7.0/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
结合上面引入,在index.ejs下可以直接初始化
<link rel="dns-prefetch" href="//cdn.mathjax.org" />
<script type="text/javascript" src="http://cdn.bootcss.com/mathjax/2.7.0/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/x-mathjax-config">
if(MathJax){
MathJax.Hub.Config({
jax: ["input/TeX","output/HTML-CSS", "output/PreviewHTML"], //输出格式配置:latex 解析为 DOM结构
tex2jax: {
inlineMath: [['$','$']],
displayMath: [ ['$$','$$'], ["\\[","\\]"] ]
},
"HTML-CSS": {
showMathMenu: false, // 隐藏右键菜单展示
linebreaks: {
automatic: true, //超长公式换行处理(默认是false不换行)
width: "80%" //设置换行的点,默认是遇到等号=换行
}
},
});
}
</script>
3.2、配置MathJax,封装globalVariable.js文件
let isMathjaxConfig = false;//用于标识是否配置
const initMathjaxConfig = () => {
if (!window.MathJax) {
return;
}
window.MathJax.Hub.Config ({
extensions: ["tex2jax.js"],
jax: ["input/TeX", "output/HTML-CSS"],
showMathMenu: false,
tex2jax: {
inlineMath: [['$', '$'], ["\\(", "\\)"]],
displayMath: [['$$', '$$'], ["\\[", "\\]"]],
processEscapes: true
},
"HTML-CSS": {availableFonts: ["TeX"]},
});
isMathjaxConfig = true; //配置完成,改为true
};
const MathQueue = function (elementId) {
if (!window.MathJax) {
return;
}
window.MathJax.Hub.Queue (["Typeset", window.MathJax.Hub]); //整个dom下渲染
// window.MathJax.Hub.Queue(["Typeset", window.MathJax.Hub, document.getElementById(elementId)]); //固定id元素渲染,
};
export default {
isMathjaxConfig,
initMathjaxConfig,
MathQueue
}
3.3、在main.js中引入并全局使用
import globalVariable from './components/config/globalVariable';
Vue.prototype.commonsVariable = globalVariable;
3.4、需要渲染的页面调用
在渲染列表方法结束之后,直接调用下面方法即可
let _this = this;
setTimeout(function () {
if(_this.commonsVariable.isMathjaxConfig){//判断是否初始配置,若无则配置。
_this.commonsVariable.initMathjaxConfig();
}
_this.commonsVariable.MathQueue("searchTextJson");//传入组件id,让组件被MathJax渲染
},500);
比如f的平方,效果图如下:
4. 更多资料
- 前端整合MathjaxJS的配置笔记 : https://www.linpx.com/p/front-end-integration-mathjaxjs-configuration.html
- Mathjax官网 : MathJax | Beautiful math in all browsers.
- Mathjax中文文档 : MathJax 中文文档 — MathJax Chinese Doc 2.0 documentation
交流
1、QQ群:可添加qq群共同进阶学习: 进军全栈工程师疑难解 群: 856402057
2、公众号:公众号「进军全栈攻城狮」 ,对前端技术保持学习爱好者。我会经常分享自己所学所看的干货,在进阶的路上,共勉!