浏览器渲染数学公式

使用 MathJax 可以在主流浏览器渲染Latex格式的数学公式,wordpress上也可以用。

主页:https://www.mathjax.org/

github:https://github.com/mathjax/MathJax

使用方式

直接引用CDN

在页面header中加入以下代码即可:

<script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
  • 其中 polyfill 库是用来提升兼容性的,可以不要

下载到本地使用

方式一:使用npm下载

npm install mathjax@3
mv node_modules/mathjax/es5 你的存放地址/mathjax

方式二:直接下载源码文件

git clone https://github.com/mathjax/MathJax.git mj-tmp
mv mj-tmp/es5 你的存放地址/mathjax

然后在项目中引用即可

<script id="MathJax-script" async src="你的存放地址/mathjax/tex-chtml.js"></script>

在nodejs项目中使用

  1. 安装包
    npm install mathjax@3
  2. 在项目中引用
    require('mathjax').init({ loader: {load: ['input/tex', 'output/svg']} // 定义MathJax 配置 }).then((MathJax) => { const svg = MathJax.tex2svg('\\frac{1}{x^2-1}', {display: true}); // 这两行将在 MathJax 加载完成之后执行 console.log(MathJax.startup.adaptor.outerHTML(svg)); }).catch((err) => console.log(err.message));

注意事项

MathJax 默认不支持使用单个 $ 作为内联公式,因为美元符号经常会被用在展示价格,容易引起冲突。应使用 \(...\) 代替 $...$

行级公式可使用 $$...$$\[...\]均可

HTML示例

创建一个html文件

<!DOCTYPE html>
<html>
<head>
<title>MathJax TeX Test Page</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
<script type="text/javascript" id="MathJax-script" async
  src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js">
</script>
</head>
<body>
When \(a \ne 0\), there are two solutions to \(ax^2 + bx + c = 0\) and they are
$$x = {-b \pm \sqrt{b^2-4ac} \over 2a}.$$
</body>
</html>

浏览器打开得到

在wordpress中使用

方式一:修改 header.php 文件

修改 /var/www/html/wp-content/themes/sacchaone/header.php 文件即可:

方式二:使用 Header Footer Code Manager 插件

使用 Header Footer Code Manager 插件在头部插入一个引入该js的脚本

  • Header Footer Code Manager 插件有的时候会保存失败,多试几次。

Leave a Comment