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官網 : https://www.mathjax.org/
- Mathjax中文文檔 : https://mathjax-chinese-doc.readthedocs.io/en/latest/
交流
可添加qq羣共同進階學習: 進軍全棧工程師疑難解 羣號: 856402057
對前端技術保持學習愛好者。我會經常分享自己所學所看的乾貨,在進階的路上,共勉!歡迎關注公衆號共同學習。