基于 KaTeX 构建的小程序原生 LaTeX 渲染组件(不依赖服务端渲染)
基于 katex 库,解析 latex 公式生成虚拟 dom 树对象,将 dom 对象翻译成小程序的 rich-text 支持的 nodes 由小程序渲染
- 依赖微信小程序的
rich-text
组件渲染,请注意小程序基础库 1.4.0 开始支持 - 由于 katex 库过大会大量占用小程序包体大小。
引入eval5
模块对象 katex 模块进行在线加载,从而减小包体大小。(2022 年 7 月 6 日起小程序不允许使用eval5)- 如果你希望再小一点,可以将解析模块放在服务端,提供解析接口,再将结果展示在 rich-text 中(已实现)
虽然这里使用了服务端,但是这里是产出json格式的nodes而非图片,相对于将latex转为图片的方案也好很多
npm install @rojer/katex-mini
@import "./miniprogram_npm/@rojer/katex-mini/index.wxss";
// index.js
import parse from "@rojer/katex-mini";
Page({
data: {
nodes: [],
latex:
"\\displaystyle \\frac{1}{\\Bigl(\\sqrt{\\phi \\sqrt{5}}-\\phi\\Bigr) e^{\\frac25 \\pi}} = 1+\\frac{e^{-2\\pi}} {1+\\frac{e^{-4\\pi}} {1+\\frac{e^{-6\\pi}} {1+\\frac{e^{-8\\pi}} {1+\\cdots} } } }",
},
onInput: function (e) {
this.setData({
latex: e.detail.value,
});
},
renderLatex: function () {
this.setData({
nodes: parse(this.data.latex),
});
},
});
<!--index.wxml-->
<view class="container">
<rich-text nodes="{{nodes}}"></rich-text>
<textarea value="{{latex}}" bindinput="onInput" maxlength="1400"></textarea>
<button bindtap="renderLatex">渲染</button>
</view>
git clone https://github.com/rojer95/katex-mini-taro-demo.git
yarn
yarn dev:weapp
- 打开小程序开发者工具, 打开 dist 目录
- 可以修改文本框内容 Latex 公式,点击渲染查看效果
API 的 Demo 源码: https://github.com/rojer95/katex-mini-api
// 在app.wxss中
@import "katex-mini.wxss";
katex-mini.wxss
的下载地址: https://cdn.jsdelivr.net/npm/@rojer/katex-mini/dist/index.wxss
wx.request({
url: "https://katex-mini-api.vercel.app",
data: {
latex: "a=b+c",
},
dataType: "json",
success(res) {
this.setData({
nodes: res.data,
});
},
});
<rich-text nodes="{{ nodes }}" />
rojer |
had0ngzhu |
如果能帮到你,希望能给我一个Star。感谢!