首页 / 基础教程

基础教程:核心概念与常用写法

Manim 的世界只有两个核心名词:Mobject(数学对象,画面上的一切)与 Animation(动画,对象随时间的变化)。掌握本文四个部分,即可独立完成一支教学短视频。

1. 场景与图形创建

每个视频片段是一个 Scene 子类,construct 中按顺序编写画面逻辑:

from manim import *

class Shapes(Scene):
    def construct(self):
        circle = Circle(radius=1.2, color=BLUE)
        square = Square(side_length=2, color=GREEN)
        self.add(circle)          # 直接放置,无动画
        self.play(Create(square)) # 带描画动画出现
        self.wait(1)

常用基础图形:Circle、Square、Rectangle、Line、Arrow、Polygon、Dot、Brace(花括号标注)。所有 Mobject 通用属性:.set_fill()、.set_stroke()、.scale()、.move_to()、.next_to()、.rotate()。

2. 播放动画

self.play() 是动画的唯一入口,常用动画类:

  • 入场:Create(描画)、Write(书写,适合文字公式)、、GrowFromCenter;
  • 变换:Transform(形状渐变)、ReplacementTransform(替换式渐变)、Rotate、ScaleInPlace;
  • 强调:Indicate、Flash、Circumscribe、Wiggle;
  • 离场:FadeOut、Unwrite。
self.play(Transform(square, circle))       # 方块渐变为圆
self.play(Indicate(circle, color=YELLOW)) # 高亮强调
self.play(FadeOut(circle))                # 淡出
同屏多个动画并行:self.play(a1, a2, run_time=2);对同一对象的连续 Transform 建议改用 ReplacementTransform,避免状态混乱。

3. 文字与公式

Text 用于普通文字(含中文,注意指定字体),MathTex 用于 LaTeX 公式(需已安装 LaTeX):

class TextAndTex(Scene):
    def construct(self):
        title = Text("勾股定理", font="Microsoft YaHei", font_size=40)
        formula = MathTex(r"a^2 + b^2 = c^2", font_size=60)
        title.to_edge(UP)
        formula.next_to(title, DOWN, buff=1)
        self.play(Write(title))
        self.play(Write(formula))
        self.wait()

排版利器 VGroup 可以把多个对象组成一组统一布局:

group = VGroup(title, formula).arrange(DOWN, buff=0.8)

4. 坐标系与函数图像

Axes 是教学视频的主力组件,配合 plot 画函数、配合 ValueTracker 做参数动画:

class PlotSin(Scene):
    def construct(self):
        axes = Axes(
            x_range=[-3, 3, 1], y_range=[-2, 2, 1],
            axis_config={"include_numbers": True},
        )
        curve = axes.plot(lambda x: np.sin(x), color=YELLOW)
        label = axes.get_graph_label(curve, "y=sin(x)")
        self.play(Create(axes))
        self.play(Create(curve), Write(label))
        self.wait()

5. 建议的学习路径

  1. 跑通本文全部示例,理解 add / play / wait 的关系;
  2. 学习 ValueTracker + always_redraw 制作随参数变化的动态图形;
  3. 尝试 Scene.next_section() 组织长视频章节,按章节渲染提升迭代效率;
  4. 阅读官方文档的 Gallery,临摹喜欢的动画效果。

更多可直接运行的完整场景,见示例代码。