MathTex 把 LaTeX 公式渲染成矢量图形,可以像普通对象一样缩放、变色、逐段拆开。示例写出质能方程,再依次变色与放大,演示公式对象的基本操作。

完整代码

1
2
3
4
5
6
7
8
9
10
11
from manim import *
class FormulaTyping(Scene):
def construct(self):
formula = MathTex(r"E = mc^2", font_size=96)
self.play(Write(formula))
self.wait(0.5)
self.play(formula.animate.set_color(YELLOW))
self.wait(0.5)
self.play(formula.animate.scale(1.4))
self.wait(1)
self.wait(0.60)

演示视频

下载 Python 脚本

要点

  • 字符串要用 raw 写法 r"...",否则反斜杠会被 Python 转义
  • MathTex 里用 \\ 换行、用多个字符串参数拆分公式片段
  • 公式默认走 LaTeX,需要本机安装 TeX 环境(Manim CE 可用 TinyTeX)

代码来源:Manim Community 官方教程 Guides / Rendering Text and Formulas,示例代码按 Manim CE 0.20.1 编写并实跑验证。