Manim 动画库教程(1)

ModelEngine·创作计划征文活动 10w+人浏览 1.3k人参与

Manim 动画库教程(1)

Mathematical Animation Engine — 高质量数学可视化的创作工具


引言

Manim(Mathematical Animation Engine)是一个强大的数学动画制作引擎,由 3Blue1Brown 的 Grant Sanderson 创建。得益于其精确的坐标系统、丰富的动画接口以及高度可控的渲染方式,Manim 已成为科研演示、课程视频以及可视化内容创作的重要工具。

本教程旨在系统介绍 Manim 的使用方法,包括安装配置、基本概念、核心动画机制以及常用高级功能,使读者能够迅速建立完整的 Manim 使用体系。


1. 安装与环境配置

1.1 系统需求

  • Python 3.7+
  • FFmpeg(视频编解码)
  • LaTeX(用于高质量数学公式渲染,可选)

1.2 安装步骤

使用 pip 安装:

pip install manim

或从源码安装:

git clone https://github.com/3b1b/manim.git
cd manim
pip install -e .

检查安装状态:

manim --version

2. Manim 的核心概念

Manim 的设计围绕三个核心组件展开:

2.1 Scene(场景)

动画的容器,每个场景渲染为独立的视频片段。所有对象的创建、动画、布局均在 Scene 的 construct() 方法中定义。

2.2 Mobject(数学对象)

Manim 中所有可见元素的基类,包括点、线、图形、文本、图像等。

2.3 Animation(动画)

描述 Mobject 随时间变化的方式,如移动、缩放、旋转、形变等。

2.4 项目结构(推荐)

project/
├── scenes/
│   ├── basic.py
│   └── advanced.py
├── assets/
│   └── images/
├── media/
└── config.yml

3. 创建第一个 Manim 动画

from manim import *

class FirstScene(Scene):
    def construct(self):
        circle = Circle()
        self.play(Create(circle))
        self.wait(1)
        self.play(circle.animate.set_fill(RED, opacity=0.5))
        self.wait(1)

使用命令渲染:

manim -pql first_scene.py FirstScene

结果展示:

在这里插入图片描述

常用参数说明:

  • -p:渲染结束后自动预览
  • -ql:低质量,适合快速测试
  • -qm:中等质量
  • -qh:高质量
  • -qk:4K 输出

4. 几何图形与绘制对象

4.1 基本几何形状

circle = Circle(radius=1.5, color=BLUE)
square = Square(side_length=2, color=RED)
triangle = Triangle(color=GREEN)
pentagon = RegularPolygon(n=5, color=YELLOW)

通过 arrange() 和坐标移动可轻松布局对象。

完整程序
# 程序名为  BasicShapes.py
from manim import *

class BasicShapes(Scene):
    def construct(self):
        # 圆形
        circle = Circle(radius=1.5, color=BLUE)
        circle.move_to(LEFT * 3)
        
        # 正方形
        square = Square(side_length=2, color=RED)
        square.move_to(RIGHT * 3)
        
        # 三角形
        triangle = Triangle(color=GREEN)
        triangle.scale(1.5)
        
        # 多边形
        pentagon = RegularPolygon(n=5, color=YELLOW)
        pentagon.move_to(UP * 2)
        
        # 显示所有形状
        self.play(
            Create(circle),
            Create(square),
            Create(triangle),
            Create(pentagon)
        )
        self.wait(2)
# 运行程序命令为: manim -pqk BasicShapes.py BasicShapes
结果展示

在这里插入图片描述

4.2 线段与箭头

line = Line(LEFT*3, RIGHT*3)
arrow = Arrow(LEFT*2, RIGHT*2)
double_arrow = DoubleArrow(LEFT*3, RIGHT*3)
curve = CurvedArrow(LEFT, RIGHT, angle=-PI/3)

这些对象在力学、场论、几何教学中非常实用。

完整程序为:
# 程序名为: LinesAndArrows.py

from manim import *

class LinesAndArrows(Scene):
    def construct(self):
        # 直线
        line = Line(LEFT * 3, RIGHT * 3, color=BLUE)
        
        # 带箭头的线
        arrow = Arrow(LEFT * 2, RIGHT * 2, color=RED, buff=0)
        
        # 双箭头
        double_arrow = DoubleArrow(LEFT * 3, RIGHT * 3, color=GREEN)
        
        # 曲线
        curve = CurvedArrow(
            LEFT * 2 + DOWN,
            RIGHT * 2 + DOWN,
            angle=-TAU/4,
            color=PURPLE
        )
        
        self.play(Create(line))
        self.play(GrowArrow(arrow))
        self.play(GrowArrow(double_arrow))
        self.play(Create(curve))
        self.wait(1)
# 运行程序命令为: manim -pqk LinesAndArrows.py LinesAndArrows
结果展示

在这里插入图片描述


5. 文本与数学公式

5.1 普通文本

title = Text("Manim 教程", font_size=48, color=BLUE)
subtitle = Text("中文示例", font_size=36, slant=ITALIC)

配合位置控制:

title.to_edge(UP)
subtitle.next_to(title, DOWN)
完整程序:
# 程序名为: TextExamples.py  
from manim import *
class TextExamples(Scene):
    def construct(self):
        # 普通文本
        title = Text("Manim教程", font_size=48, color=BLUE)
        title.to_edge(UP)
        
        # 不同字体
        bold_text = Text("Persus Crab", weight=BOLD, font_size=36)
        italic_text = Text("Persus Crab", slant=ITALIC, font_size=36)
        
        # 排列文本
        bold_text.next_to(title, DOWN, buff=1.5)
        italic_text.next_to(bold_text, DOWN, buff=1.3)
        
        self.play(Write(title))
        self.play(Write(bold_text))
        self.play(Write(italic_text))
        self.wait(1)
# 运行程序命令为: manim -pqk TextExamples.py   TextExamples
结果展示

在这里插入图片描述

5.2 数学公式

Manim 提供 LaTeX 数学公式渲染:

eq1 = MathTex(r"E = mc^2")
eq2 = MathTex(r"\int e^{-x^2} dx = \sqrt{\pi}")

不同复杂度的公式均可流畅呈现。

完整代码
# 程序名为:MathFormulas.py

from manim import *

class MathFormulas(Scene):
    def construct(self):
        # 行内公式
        equation1 = MathTex(r"E = mc^2", font_size=48,color=RED)
        equation1.to_edge(UP)
        
        # 复杂公式
        equation2 = MathTex(
            r"\int_{-\infty}^{\infty} e^{-x^2} dx = \sqrt{\pi}",
            font_size=36,
            color=BLUE
        )
        equation2.next_to(equation1, DOWN, buff=0.5)
        
        # 分步显示公式
        equation3 = MathTex(
            r"f(x) = \frac{1}{\sqrt{2\pi\sigma^2}} e^{-\frac{(x-\mu)^2}{2\sigma^2}}",
            font_size=32,
            color=GREEN
        )
        equation3.next_to(equation2, DOWN, buff=0.5)
        
        self.play(Write(equation1))
        self.play(Write(equation2))
        self.play(Write(equation3))
        self.wait(2)
# 运行命令为: manim -qm --format=gif  MathFormulas.py  

结果展示

在这里插入图片描述

5.3 代码显示

code = Code(
    code_string=\"\"\"def add(a,b): return a+b\"\"\",
    language="Python",
    background="window"
)

适用于教学、技术演示等场景。

完整代码
# 程序名为:CodeExample.py

from manim import *

class CodeExample(Scene):
    def construct(self):
        code_str = '''
def fibonacci(n):
    if n <= 1:
        return n
    else:
        return fibonacci(n-1) + fibonacci(n-2)
'''
        code = Code(
            code_string=code_str,
            tab_width=4,
            background="window",
            language="Python"
        )
        
        self.play(Write(code))
        self.wait(2)

# 运行命令为: manim -qm --format=gif CodeExample.py

结果展示

在这里插入图片描述


6. 动画与变换

Manim 最核心的能力来自灵活且可组合的动画系统。

6.1 对象变换

self.play(circle.animate.shift(RIGHT*2))
self.play(circle.animate.scale(1.5))
self.play(Rotate(circle, angle=PI/2))

6.2 对象之间的形变

self.play(Transform(circle, square))

6.3 动画序列与组合

self.play(
    shape1.animate.shift(UP),
    shape2.animate.rotate(PI/2),
    shape3.animate.scale(1.2),
    run_time=2
)

6.4 沿路径运动

path = Arc(radius=2, angle=PI)
self.play(MoveAlongPath(dot, path))
完整代码
# 程序名为:Transformations.py
from manim import *
class Transformations(Scene):
    def construct(self):
        # 创建初始对象
        circle = Circle(color=RED, fill_opacity=0.8)
        square = Square(color=BLUE, fill_opacity=0.8)
        triangle = Triangle(color=GREEN, fill_opacity=0.8)
        
        # 排列对象
        circle.move_to(LEFT * 3)
        square.move_to(ORIGIN)
        triangle.move_to(RIGHT * 3)
        
        self.play(Create(circle), Create(square), Create(triangle))
        self.wait(1)
        
        # 变换动画
        self.play(Transform(circle, square.copy()))
        self.wait(0.5)
        
        self.play(Transform(square, triangle.copy()))
        self.wait(0.5)
        
        self.play(Transform(triangle, circle.copy()))
        self.wait(1)
# 运行命令:manim -qm --format=gif Transformations.py
结果展示

在这里插入图片描述


7. 坐标系与图形绘制

Manim 的坐标系统适合数学函数绘图和数据可视化。

7.1 构建坐标系

axes = Axes(
    x_range=[-3, 3, 1],
    y_range=[-2, 2, 1]
)

7.2 绘制函数图像

graph = axes.plot(lambda x: np.sin(x), color=YELLOW)
label = axes.get_graph_label(graph, label="\\sin(x)")

7.3 标注点与移动

dot = Dot().move_to(axes.coords_to_point(PI/2, 1))
self.play(GrowFromCenter(dot))
完整代码
# 程序名为:CoordinateSystemExample.py
from manim import *
class CoordinateSystemExample(Scene):
    def construct(self):
        # 创建坐标系
        axes = Axes(
            x_range=[-3, 3, 1],
            y_range=[-3, 3, 1],
            x_length=6,
            y_length=6,
            axis_config={"color": BLUE},
        )
        
        # 添加坐标标签
        axis_labels = axes.get_axis_labels(x_label="x", y_label="y")
        
        # 创建函数图形
        graph = axes.plot(lambda x: np.sin(x), color=YELLOW)
        
        # 显示所有元素
        self.play(Create(axes), Write(axis_labels))
        self.play(Create(graph))
        self.wait(1)
        
        # 添加点
        dot = Dot(color=RED).move_to(axes.coords_to_point(0, 0))
        self.play(GrowFromCenter(dot))
        
        # 移动点
        self.play(dot.animate.move_to(axes.coords_to_point(PI/2, 1)))
        self.wait(1)

# 运行命令:manim -qm --format=gif  CoordinateSystemExample.py

结果展示

在这里插入图片描述


8. 实用技巧与最佳实践

8.1 项目配置

可通过 config.pyconfig.yml 设置全局参数:

config.background_color = WHITE
config.frame_width = 16
config.frame_height = 9
Text.set_default(color=BLACK)

8.2 输出格式

# MP4 视频
manim -pqh scene.py Example

# GIF
manim -pqh --format=gif scene.py Example

# PNG 图片
manim -pql --format=png scene.py Example

8.3 性能优化

  • 使用 VGroup 管理大量对象
  • 合理使用 lag_ratio 减少瞬时负荷
  • 尽可能避免逐帧 Python 循环

结语

Manim 通过数学化的动画表达方式,可以为教育、科研与可视化领域提供极具创造力的工具。本教程覆盖 Manim 的基础能力与常用模式。
希望可以帮助到各位友友!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Persus

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值