angular 12 显示数学公式
2021年7月16日 06:34
编程技术
angular 12 显示数学公式
公式的格式
主要有两种写法格式:
LaTeXAsciiMath
安装依赖
这里使用的是 KaTeX,默认支持 LaTeX,如果需要支持 AsciiMath 则需要 安装转化工具 asciimath2tex
npm i katex
npm i asciimath2tex
默认是有 angular 版本的 KaTeX
npm i ng-katex
注意
ng-katex 默认根据 $ 和 $$ 来识别处理公式的
例如
$a=x^2$
代码
但是我不知需要显示公式,还需要处理一些其他的,所以直接使用 KaTeX 进行处理
npm i katex
npm i asciimath2tex
import * as katex from 'katex';
import AsciiMathParser from 'asciimath2tex';
    private formatContent() {
        const items: IMarkItem[] = [];
        const content = this.content.trim();
        let index = -1;
        let start = 0;
        const parser = new AsciiMathParser();
        const pushMath = () => {
            index ++;
            start = index;
            while (index < content.length - 1) {
                if (content.charAt(++index) === '$'  && backslashedCount(index - 1) % 2 === 0) {
                    break;
                }
            }
            items.push({
                type: 'math',
                content: this.sanitizer.bypassSecurityTrustHtml(
                    katex.renderToString(parser.parse(content.substring(start, index)))
                )
            });
        };
        const pushText = (end: number) => {
            if (end > content.length) {
                end = content.length;
            }
            if (start >= end) {
                return;
            }
            const text = content.substring(start, end);
            if (text.length < 1) {
                return;
            }
            items.push({
                type: 'text',
                content: text,
            });
        };
        const backslashedCount = (i: number) => {
            let count = 0;
            while (i >= 0) {
                if (content.charAt(i --) === '\\') {
                    count ++;
                    continue;
                }
                break;
            }
            return count;...剩余内容已隐藏
查看完整文章以阅读更多