高仿知乎数学公式服务器端 svg 处理

yufei       4 年, 8 月 前       1205

知乎的数学公式采用的是服务器端生成的。比如下面的数学公式

的地址为

https://www.zhihu.com/equation?tex=%5Ccolor%7Bred%7D%7B%7CAB%7C%3D2%5Csqrt%7Br%5E2-d%5E2%7D%7D

这里,我们也模仿这种处理方式,来实现数学公式的后端 svg 显示

  1. 首先安装必须的 node 模块

    npm install mathjax-node
    
  2. 然后在某个目录下新建 app.js 内容如下

    var mjAPI = require("mathjax-node");
    mjAPI.config({MathJax: {},displayErrors:false});
    mjAPI.start();
    
    const http = require('http');
    const url = require("url");
    
    const hostname = '127.0.0.1';
    const port = 3000;
    
    const server = http.createServer((req, res) => {
    
      var parsed_url = url.parse(req.url,true);
      var query = parsed_url.query;
    
      if(parsed_url.pathname != '/equation')
      {
        res.setHeader('Content-Type', 'text/plain');
        res.end('Hello, World!\n');
        return;  
      }
    
       var tex =  parsed_url.query.tex ? parsed_url.query.tex : '';
    
        mjAPI.typeset({
            math: tex,
            format: "TeX",
            speakText:false,
            svg:true,
          }, function (data) {
            res.setHeader('Content-Type', 'image/svg+xml');
            if (!data.errors) {
              res.end(data.svg);
            } else {
              res.end('<svg xmlns:xlink="http://www.w3.org/1999/xlink" width="0" height="0.343ex" style="vertical-align: -0.171ex;" viewBox="0 -73.8 0 147.5" role="img" focusable="false" xmlns="http://www.w3.org/2000/svg" aria-labelledby="MathJax-SVG-1-Title"><defs aria-hidden="true"></defs><g stroke="currentColor" fill="currentColor" stroke-width="0" transform="matrix(1 0 0 -1 0 0)" aria-hidden="true"></g></svg>');
            }
        });
    });
    
    server.listen(port, hostname, () => {
      console.log(`Server running at http://${hostname}:${port}/`);
    });
    
  3. 然后通过运行下面的命令开启 web 服务

    node main.js
    

完成上面的步骤之后,我们就可以通过下面的 url 来查看 mathjax 数学公式了

http://localhost:3000/equation?tex=%5Ccolor%7Bred%7D%7B%7CAB%7C%3D2%5Csqrt%7Br%5E2-d%5E2%7D%7D

目前尚无回复
简单教程 = 简单教程,简单编程
简单教程 是一个关于技术和学习的地方
现在注册
已注册用户请 登入
关于   |   FAQ   |   我们的愿景   |   广告投放   |  博客

  简单教程,简单编程 - IT 入门首选站

Copyright © 2013-2022 简单教程 twle.cn All Rights Reserved.