API 参考:动画(animation)

共 76 个类,按字母排序。每个类含中文说明、继承链、参数表与上手示例,API 文档由 autodoc 从 manim v0.21.0 源码自动生成;带完整中文精讲的类见 API 索引。

Add

把 Mobject 加入场景播放序列的动画:与其他动画组合时控制「何时真正把对象放上来」,常与 Succession 搭配精排时序。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "Add"; }

参数

快速上手

self.play(Add(dot))

API 文档

class manim.Add(mobject=None, *args, use_override=True, **kwargs)

基类:Animation

Add Mobjects to a scene, without animating them in any other way. This is similar to the Scene.add() method, but Add is an animation which can be grouped into other animations.

Parameters

mobjects

One Mobject or more to add to a scene.

run_time

The duration of the animation after adding the mobjects. Defaults to 0, which means this is an instant animation without extra wait time after adding them.

**kwargs

Additional arguments to pass to the parent Animation class.

Examples

class DefaultAddScene(Scene):
    def construct(self):
        text_1 = Text("I was added with Add!")
        text_2 = Text("Me too!")
        text_3 = Text("And me!")
        texts = VGroup(text_1, text_2, text_3).arrange(DOWN)
        rect = SurroundingRectangle(texts, buff=0.5)

        self.play(
            Create(rect, run_time=3.0),
            Succession(
                Wait(1.0),
                # You can Add a Mobject in the middle of an animation...
                Add(text_1),
                Wait(1.0),
                # ...or multiple Mobjects at once!
                Add(text_2, text_3),
            ),
        )
        self.wait()
class AddWithRunTimeScene(Scene):
    def construct(self):
        # A 5x5 grid of circles
        circles = VGroup(
            *[Circle(radius=0.5) for _ in range(25)]
        ).arrange_in_grid(5, 5)

        self.play(
            Succession(
                # Add a run_time of 0.2 to wait for 0.2 seconds after
                # adding the circle, instead of using Wait(0.2) after Add!
                *[Add(circle, run_time=0.2) for circle in circles],
                rate_func=smooth,
            )
        )
        self.wait()
begin() → None

Begin the animation.

This method is called right as an animation is being played. As much initialization as possible, especially any mobject copying, should live in this method.

clean_up_from_scene(scene: Scene) → None

Clean up the Scene after finishing the animation.

This includes to remove() the Animation's Mobject if the animation is a remover.

Parameters
scene

The scene the animation should be cleaned up from.

finish() → None

Finish the animation.

This method gets called when the animation is over.

interpolate(alpha: float) → None

Set the animation progress.

This method gets called for every frame during an animation.

Parameters
alpha

The relative time to set the animation to, 0 meaning the start, 1 meaning the end.

update_mobjects(dt: float) → None

Updates things like starting_mobject, and (for Transforms) target_mobject. Note, since typically (always?) self.mobject will have its updating suspended during the animation, this will do nothing to self.mobject.

AddTextLetterByLetter

让 Text 逐字母浮现,每个字母带微小放大效果,模拟打字机输入,可设置每字符耗时。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "ShowIncreasingSubsets"; "ShowIncreasingSubsets" -> "AddTextLetterByLetter"; }

参数

text

—,Text

suspend_mobject_updating

False,bool

int_func

<ufunc 'ceil'>

rate_func

<function linear at 0x7f4ff…,Callable[[float], float]

time_per_char

0.1,float

run_time

None,float | None

reverse_rate_function

False

introducer

True

快速上手

self.play(AddTextLetterByLetter(text))

API 文档

class manim.AddTextLetterByLetter(mobject=None, *args, use_override=True, **kwargs)

基类:ShowIncreasingSubsets

Show a Text letter by letter on the scene.

Parameters

time_per_char

Frequency of appearance of the letters.

小技巧

This is currently only possible for class:~.Text and not for class:~.MathTex

AddTextWordByWord

让 Text 逐词浮现,按空格分词,适合字幕式进场。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "AnimationGroup"; "AnimationGroup" -> "Succession"; "Succession" -> "AddTextWordByWord"; }

参数

text_mobject

—,Text

run_time

None,float

time_per_char

0.06,float

快速上手

self.play(AddTextWordByWord(text))

API 文档

class manim.AddTextWordByWord(mobject=None, *args, use_override=True, **kwargs)

基类:Succession

Show a Text word by word on the scene. Note: currently broken.

AnimatedBoundary

围绕 VMobject 持续流动的虚线边界动画,常用于高亮某个对象「正在被讨论」。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Mobject" -> "VMobject"; "VMobject" -> "VGroup"; "VGroup" -> "AnimatedBoundary"; }

参数

vmobject

—,VMobject

colors

[ManimColor('#29ABCA'), Man…

max_stroke_width

3,float

cycle_rate

0.5,float

back_and_forth

True,bool

draw_rate_func

<function smooth at 0x7f4ff…,RateFunction

fade_rate_func

<function smooth at 0x7f4ff…,RateFunction

快速上手

self.add(AnimatedBoundary(circle))

API 文档

class manim.AnimatedBoundary(vmobject: ~manim.mobject.types.vectorized_mobject.VMobject, colors: ~collections.abc.Sequence[~manim.utils.color.core.ManimColor | int | str | ~numpy._typing._array_like.NDArray[~numpy.int64] | tuple[int, int, int] | ~numpy._typing._array_like.NDArray[~numpy.float64] | tuple[float, float, float] | tuple[int, int, int, int] | tuple[float, float, float, float]] = [ManimColor('#29ABCA'), ManimColor('#9CDCEB'), ManimColor('#236B8E'), ManimColor('#736357')], max_stroke_width: float = 3, cycle_rate: float = 0.5, back_and_forth: bool = True, draw_rate_func: ~manim.utils.rate_functions.RateFunction = <function smooth>, fade_rate_func: ~manim.utils.rate_functions.RateFunction = <function smooth>, **kwargs: ~typing.Any)

基类:VGroup

Boundary of a VMobject with animated color change.

Examples

class AnimatedBoundaryExample(Scene):
    def construct(self):
        text = Text("So shiny!")
        boundary = AnimatedBoundary(text, colors=[RED, GREEN, BLUE],
                                    cycle_rate=3)
        self.add(text, boundary)
        self.wait(2)

Animation

一切动画的基类。自定义动画时继承它并实现 interpolate():给定 alpha(0 到 1)描述画面状态。

参数

mobject

—

lag_ratio

0.0,float

run_time

1.0,float

rate_func

<function smooth at 0x7f4ff…,Callable[[float], float]

reverse_rate_function

False,bool

name

None,str

remover

False,bool

suspend_mobject_updating

True,bool

introducer

False,bool

_on_finish

<function Animation.<lambda…,Callable[[Scene], None]

use_override

True,bool

快速上手

class Fade(Animation):
    def interpolate(self, alpha):
        self.mobject.set_opacity(alpha)

API 文档

class manim.Animation(mobject=None, *args, use_override=True, **kwargs)

基类:object

An animation.

Animations have a fixed time span.

Parameters

mobject

The mobject to be animated. This is not required for all types of animations.

lag_ratio

Defines the delay after which the animation is applied to submobjects. This lag is relative to the duration of the animation.

This does not influence the total runtime of the animation. Instead the runtime of individual animations is adjusted so that the complete animation has the defined run time.

run_time

The duration of the animation in seconds.

rate_func

The function defining the animation progress based on the relative runtime (see rate_functions) .

For example rate_func(0.5) is the proportion of the animation that is done after half of the animations run time.

reverse_rate_function

Reverses the rate function of the animation. Setting reverse_rate_function does not have any effect on remover or introducer. These need to be set explicitly if an introducer-animation should be turned into a remover one and vice versa.

name

The name of the animation. This gets displayed while rendering the animation. Defaults to <class-name>(<Mobject-name>).

remover

Whether the given mobject should be removed from the scene after this animation.

suspend_mobject_updating

Whether updaters of the mobject should be suspended during the animation.

备注

In the current implementation of this class, the specified rate function is applied within Animation.interpolate_mobject() call as part of the call to Animation.interpolate_submobject(). For subclasses of Animation that are implemented by overriding interpolate_mobject(), the rate function has to be applied manually (e.g., by passing self.rate_func(alpha) instead of just alpha).

Examples

class LagRatios(Scene):
    def construct(self):
        ratios = [0, 0.1, 0.5, 1, 2]  # demonstrated lag_ratios

        # Create dot groups
        group = VGroup(*[Dot() for _ in range(4)]).arrange_submobjects()
        groups = VGroup(*[group.copy() for _ in ratios]).arrange_submobjects(buff=1)
        self.add(groups)

        # Label groups
        self.add(Text("lag_ratio = ", font_size=36).next_to(groups, UP, buff=1.5))
        for group, ratio in zip(groups, ratios):
            self.add(Text(str(ratio), font_size=36).next_to(group, UP))

        #Animate groups with different lag_ratios
        self.play(AnimationGroup(*[
            group.animate(lag_ratio=ratio, run_time=1.5).shift(DOWN * 2)
            for group, ratio in zip(groups, ratios)
        ]))

        # lag_ratio also works recursively on nested submobjects:
        self.play(groups.animate(run_time=1, lag_ratio=0.1).shift(UP * 2))
begin() → None

Begin the animation.

This method is called right as an animation is being played. As much initialization as possible, especially any mobject copying, should live in this method.

clean_up_from_scene(scene: Scene) → None

Clean up the Scene after finishing the animation.

This includes to remove() the Animation's Mobject if the animation is a remover.

Parameters
scene

The scene the animation should be cleaned up from.

copy() → Animation

Create a copy of the animation.

Returns
Animation

A copy of self

finish() → None

Finish the animation.

This method gets called when the animation is over.

get_all_mobjects() → Sequence[Mobject | OpenGLMobject]

Get all mobjects involved in the animation.

Ordering must match the ordering of arguments to interpolate_submobject

Returns
Sequence[Mobject]

The sequence of mobjects.

get_all_mobjects_to_update() → list[Mobject]

Get all mobjects to be updated during the animation.

Returns
List[Mobject]

The list of mobjects to be updated during the animation.

get_rate_func() → Callable[[float], float]

Get the rate function of the animation.

Returns
Callable[[float], float]

The rate function of the animation.

get_run_time() → float

Get the run time of the animation.

Returns
float

The time the animation takes in seconds.

get_sub_alpha(alpha: float, index: int, num_submobjects: int) → float

Get the animation progress of any submobjects subanimation.

Parameters
alpha

The overall animation progress

index

The index of the subanimation.

num_submobjects

The total count of subanimations.

Returns
float

The progress of the subanimation.

interpolate(alpha: float) → None

Set the animation progress.

This method gets called for every frame during an animation.

Parameters
alpha

The relative time to set the animation to, 0 meaning the start, 1 meaning the end.

interpolate_mobject(alpha: float) → None

Interpolates the mobject of the Animation based on alpha value.

Parameters
alpha

A float between 0 and 1 expressing the ratio to which the animation is completed. For example, alpha-values of 0, 0.5, and 1 correspond to the animation being completed 0%, 50%, and 100%, respectively.

is_introducer() → bool

Test if the animation is an introducer.

Returns
bool

True if the animation is an introducer, False otherwise.

is_remover() → bool

Test if the animation is a remover.

Returns
bool

True if the animation is a remover, False otherwise.

classmethod set_default(**kwargs) → None

Sets the default values of keyword arguments.

If this method is called without any additional keyword arguments, the original default values of the initialization method of this class are restored.

Parameters
kwargs

Passing any keyword argument will update the default values of the keyword arguments of the initialization function of this class.

Examples
class ChangeDefaultAnimation(Scene):
    def construct(self):
        Rotate.set_default(run_time=2, rate_func=rate_functions.linear)
        Indicate.set_default(color=None)

        S = Square(color=BLUE, fill_color=BLUE, fill_opacity=0.25)
        self.add(S)
        self.play(Rotate(S, PI))
        self.play(Indicate(S))

        Rotate.set_default()
        Indicate.set_default()
set_name(name: str) → Animation

Set the name of the animation.

Parameters
name

The new name of the animation.

Returns
Animation

self

set_rate_func(rate_func: Callable[[float], float]) → Animation

Set the rate function of the animation.

Parameters
rate_func

The new function defining the animation progress based on the relative runtime (see rate_functions).

Returns
Animation

self

set_run_time(run_time: float) → Animation

Set the run time of the animation.

Parameters
run_time

The new time the animation should take in seconds.

备注

The run_time of an animation should not be changed while it is already running.

Returns
Animation

self

update_mobjects(dt: float) → None

Updates things like starting_mobject, and (for Transforms) target_mobject. Note, since typically (always?) self.mobject will have its updating suspended during the animation, this will do nothing to self.mobject.

AnimationGroup

把多个动画打包同时播放,可用 lag_ratio 让组内动画依次错开,是最常用的复合动画容器。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "AnimationGroup"; }

参数

group

None

run_time

None,float | None

rate_func

<function linear at 0x7f4ff…,Callable[[float], float]

lag_ratio

0,float

快速上手

self.play(AnimationGroup(FadeIn(a), GrowFromCenter(b), lag_ratio=0.5))

API 文档

class manim.AnimationGroup(mobject=None, *args, use_override=True, **kwargs)

基类:Animation

Plays a group or series of Animation.

Parameters

animations

Sequence of Animation objects to be played.

group

A group of multiple Mobject.

run_time

The duration of the animation in seconds.

rate_func

The function defining the animation progress based on the relative runtime (see rate_functions) .

lag_ratio

Defines the delay after which the animation is applied to submobjects. A lag_ratio of n.nn means the next animation will play when nnn% of the current animation has played. Defaults to 0.0, meaning that all animations will be played together.

This does not influence the total runtime of the animation. Instead the runtime of individual animations is adjusted so that the complete animation has the defined run time.

begin() → None

Begin the animation.

This method is called right as an animation is being played. As much initialization as possible, especially any mobject copying, should live in this method.

build_animations_with_timings() → None

Creates a list of triplets of the form (anim, start_time, end_time).

clean_up_from_scene(scene: Scene) → None

Clean up the Scene after finishing the animation.

This includes to remove() the Animation's Mobject if the animation is a remover.

Parameters
scene

The scene the animation should be cleaned up from.

finish() → None

Finish the animation.

This method gets called when the animation is over.

get_all_mobjects() → Sequence[Mobject | OpenGLMobject]

Get all mobjects involved in the animation.

Ordering must match the ordering of arguments to interpolate_submobject

Returns
Sequence[Mobject]

The sequence of mobjects.

init_run_time(run_time: float | None) → float

Calculates the run time of the animation, if different from run_time.

Parameters
run_time

The duration of the animation in seconds.

Returns
run_time

The duration of the animation in seconds.

interpolate(alpha: float) → None

Set the animation progress.

This method gets called for every frame during an animation.

Parameters
alpha

The relative time to set the animation to, 0 meaning the start, 1 meaning the end.

update_mobjects(dt: float) → None

Updates things like starting_mobject, and (for Transforms) target_mobject. Note, since typically (always?) self.mobject will have its updating suspended during the animation, this will do nothing to self.mobject.

ApplyComplexFunction

把复变函数作用到每个点的复坐标上,适合做共形变换等复分析可视化。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "Transform"; "Transform" -> "ApplyMethod"; "ApplyMethod" -> "ApplyComplexFunction"; }

参数

function

—,types.MethodType

mobject

—,Mobject

快速上手

self.play(ApplyComplexFunction(lambda z: z**2, plane))

API 文档

class manim.ApplyComplexFunction(mobject=None, *args, use_override=True, **kwargs)

基类:ApplyMethod

ApplyFunction

用任意函数逐点变形 Mobject:先复制再插值到新形状,直观展示函数对图形的变换效果。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "Transform"; "Transform" -> "ApplyFunction"; }

参数

function

—,types.MethodType

mobject

—,Mobject

快速上手

self.play(ApplyFunction(lambda m: m.shift(UP), mob))

API 文档

class manim.ApplyFunction(mobject=None, *args, use_override=True, **kwargs)

基类:Transform

ApplyMatrix

用 2×2 矩阵对平面做线性变换,传入 numpy 矩阵即可,线性代数课的标配。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "Transform"; "Transform" -> "ApplyMethod"; "ApplyMethod" -> "ApplyPointwiseFunction"; "ApplyPointwiseFunction" -> "ApplyMatrix"; }

参数

matrix

—,np.ndarray

mobject

—,Mobject

about_point

array([0., 0., 0.]),np.ndarray

快速上手

self.play(ApplyMatrix([[1, 1], [0, 1]], square))

API 文档

class manim.ApplyMatrix(mobject=None, *args, use_override=True, **kwargs)

基类:ApplyPointwiseFunction

Applies a matrix transform to an mobject.

Parameters

matrix

The transformation matrix.

mobject

The Mobject.

about_point

The origin point for the transform. Defaults to ORIGIN.

kwargs

Further keyword arguments that are passed to ApplyPointwiseFunction.

Examples

class ApplyMatrixExample(Scene):
    def construct(self):
        matrix = [[1, 1], [0, 2/3]]
        self.play(ApplyMatrix(matrix, Text("Hello World!")), ApplyMatrix(matrix, NumberPlane()))

ApplyMethod

把任意 Mobject 方法(如 shift、set_color)包装成动画播放,是 mobject.animate 语法的底层实现。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "Transform"; "Transform" -> "ApplyMethod"; }

参数

快速上手

self.play(ApplyMethod(dot.shift, UP))

API 文档

class manim.ApplyMethod(mobject=None, *args, use_override=True, **kwargs)

基类:Transform

Animates a mobject by applying a method.

Note that only the method needs to be passed to this animation, it is not required to pass the corresponding mobject. Furthermore, this animation class only works if the method returns the modified mobject.

Parameters

method

The method that will be applied in the animation.

args

Any positional arguments to be passed when applying the method.

kwargs

Any keyword arguments passed to Transform.

ApplyPointwiseFunction

对曲线上每个点应用 R³ 向量函数,比 ApplyFunction 更底层,直接操作点集。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "Transform"; "Transform" -> "ApplyMethod"; "ApplyMethod" -> "ApplyPointwiseFunction"; }

参数

function

—,types.MethodType

mobject

—,Mobject

run_time

3.0,float

快速上手

self.play(ApplyPointwiseFunction(lambda p: p + UP, line))

API 文档

class manim.ApplyPointwiseFunction(mobject=None, *args, use_override=True, **kwargs)

基类:ApplyMethod

Animation that applies a pointwise function to a mobject.

Examples

class WarpSquare(Scene):
    def construct(self):
        square = Square()
        self.play(
            ApplyPointwiseFunction(
                lambda point: complex_to_R3(np.exp(R3_to_complex(point))), square
            )
        )
        self.wait()

ApplyPointwiseFunctionToCenter

以对象中心为原点应用逐点函数,避免整体平移,适合「原地扭曲」效果。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "Transform"; "Transform" -> "ApplyMethod"; "ApplyMethod" -> "ApplyPointwiseFunction"; "ApplyPointwiseFunction" -> "ApplyPointwiseFunctionToCenter"; }

参数

function

—,types.MethodType

mobject

—,Mobject

API 文档

class manim.ApplyPointwiseFunctionToCenter(mobject=None, *args, use_override=True, **kwargs)

基类:ApplyPointwiseFunction

begin() → None

Begin the animation.

This method is called right as an animation is being played. As much initialization as possible, especially any mobject copying, should live in this method.

ApplyWave

让 VMobject 产生沿路径传播的波浪形变,给静态曲线注入流动感。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "Homotopy"; "Homotopy" -> "ApplyWave"; }

参数

mobject

—,Mobject

direction

array([0., 1., 0.]),Vector3DLike

amplitude

0.2,float

wave_func

<function smooth at 0x7f4ff…,RateFunction

time_width

1,float

ripples

1,int

run_time

2,float

快速上手

self.play(ApplyWave(sine_curve))

API 文档

class manim.ApplyWave(mobject=None, *args, use_override=True, **kwargs)

基类:Homotopy

Send a wave through the Mobject distorting it temporarily.

Parameters

mobject

The mobject to be distorted.

direction

The direction in which the wave nudges points of the shape

amplitude

The distance points of the shape get shifted

wave_func

The function defining the shape of one wave flank.

time_width

The length of the wave relative to the width of the mobject.

ripples

The number of ripples of the wave

run_time

The duration of the animation.

Examples

class ApplyingWaves(Scene):
    def construct(self):
        tex = Tex("WaveWaveWaveWaveWave").scale(2)
        self.play(ApplyWave(tex))
        self.play(ApplyWave(
            tex,
            direction=RIGHT,
            time_width=0.5,
            amplitude=0.3
        ))
        self.play(ApplyWave(
            tex,
            rate_func=linear,
            ripples=4
        ))

Broadcast

从中心向外扩散一圈圈涟漪的强调动画,类似水波或雷达扩散。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "AnimationGroup"; "AnimationGroup" -> "LaggedStart"; "LaggedStart" -> "Broadcast"; }

参数

mobject

—,Mobject

focal_point

array([0., 0., 0.]),Sequence[float]

n_mobs

5,int

initial_opacity

1,float

final_opacity

0,float

initial_width

0.0,float

remover

True,bool

lag_ratio

0.2,float

run_time

3,float

快速上手

self.play(Broadcast(dot))

API 文档

class manim.Broadcast(mobject=None, *args, use_override=True, **kwargs)

基类:LaggedStart

Broadcast a mobject starting from an initial_width, up to the actual size of the mobject.

Parameters

mobject

The mobject to be broadcast.

focal_point

The center of the broadcast, by default ORIGIN.

n_mobs

The number of mobjects that emerge from the focal point, by default 5.

initial_opacity

The starting stroke opacity of the mobjects emitted from the broadcast, by default 1.

final_opacity

The final stroke opacity of the mobjects emitted from the broadcast, by default 0.

initial_width

The initial width of the mobjects, by default 0.0.

remover

Whether the mobjects should be removed from the scene after the animation, by default True.

lag_ratio

The time between each iteration of the mobject, by default 0.2.

run_time

The total duration of the animation, by default 3.

kwargs

Additional arguments to be passed to LaggedStart.

Examples

class BroadcastExample(Scene):
    def construct(self):
        mob = Circle(radius=4, color=TEAL_A)
        self.play(Broadcast(mob))

ChangeDecimalToValue

把 DecimalNumber 从当前值滚动变化到目标值的动画,数字变动平滑自然。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "ChangingDecimal"; "ChangingDecimal" -> "ChangeDecimalToValue"; }

参数

decimal_mob

—,DecimalNumber

target_number

—,int

快速上手

self.play(ChangeDecimalToValue(number, 3.14))

API 文档

class manim.ChangeDecimalToValue(mobject=None, *args, use_override=True, **kwargs)

基类:ChangingDecimal

Animate a DecimalNumber to a target value using linear interpolation.

Parameters

decimal_mob

The DecimalNumber instance to animate.

target_number

The target value to transition to.

Examples

class ChangeDecimalToValueExample(Scene):
    def construct(self):
        number = DecimalNumber(0)
        self.add(number)
        self.play(ChangeDecimalToValue(number, 10, run_time=3))
        self.wait()

ChangeSpeed

包裹一个动画并动态改变其播放速度,speed_func 接收运行进度返回速度倍率。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "ChangeSpeed"; }

参数

anim

—

speedinfo

—,dict[float, float]

rate_func

None

affects_speed_updaters

True,bool

API 文档

class manim.ChangeSpeed(mobject=None, *args, use_override=True, **kwargs)

基类:Animation

Modifies the speed of passed animation. AnimationGroup with different lag_ratio can also be used which combines multiple animations into one. The run_time of the passed animation is changed to modify the speed.

Parameters

anim

Animation of which the speed is to be modified.

speedinfo

Contains nodes (percentage of run_time) and its corresponding speed factor.

rate_func

Overrides rate_func of passed animation, applied before changing speed.

Examples

class SpeedModifierExample(Scene):
    def construct(self):
        a = Dot().shift(LEFT * 4)
        b = Dot().shift(RIGHT * 4)
        self.add(a, b)
        self.play(
            ChangeSpeed(
                AnimationGroup(
                    a.animate(run_time=1).shift(RIGHT * 8),
                    b.animate(run_time=1).shift(LEFT * 8),
                ),
                speedinfo={0.3: 1, 0.4: 0.1, 0.6: 0.1, 1: 1},
                rate_func=linear,
            )
        )
class SpeedModifierUpdaterExample(Scene):
    def construct(self):
        a = Dot().shift(LEFT * 4)
        self.add(a)

        ChangeSpeed.add_updater(a, lambda x, dt: x.shift(RIGHT * 4 * dt))
        self.play(
            ChangeSpeed(
                Wait(2),
                speedinfo={0.4: 1, 0.5: 0.2, 0.8: 0.2, 1: 1},
                affects_speed_updaters=True,
            )
        )
class SpeedModifierUpdaterExample2(Scene):
    def construct(self):
        a = Dot().shift(LEFT * 4)
        self.add(a)

        ChangeSpeed.add_updater(a, lambda x, dt: x.shift(RIGHT * 4 * dt))
        self.wait()
        self.play(
            ChangeSpeed(
                Wait(),
                speedinfo={1: 0},
                affects_speed_updaters=True,
            )
        )
classmethod add_updater(mobject: Mobject, update_function: Updater, index: int | None = None, call_updater: bool = False)

This static method can be used to apply speed change to updaters.

This updater will follow speed and rate function of any ChangeSpeed animation that is playing with affects_speed_updaters=True. By default, updater functions added via the usual Mobject.add_updater() method do not respect the change of animation speed.

Parameters
mobject

The mobject to which the updater should be attached.

update_function

The function that is called whenever a new frame is rendered.

index

The position in the list of the mobject's updaters at which the function should be inserted.

call_updater

If True, calls the update function when attaching it to the mobject.

See also

ChangeSpeed Mobject.add_updater()

begin() → None

Begin the animation.

This method is called right as an animation is being played. As much initialization as possible, especially any mobject copying, should live in this method.

clean_up_from_scene(scene: Scene) → None

Clean up the Scene after finishing the animation.

This includes to remove() the Animation's Mobject if the animation is a remover.

Parameters
scene

The scene the animation should be cleaned up from.

finish() → None

Finish the animation.

This method gets called when the animation is over.

get_scaled_total_time() → float

The time taken by the animation under the assumption that the run_time is 1.

interpolate(alpha: float) → None

Set the animation progress.

This method gets called for every frame during an animation.

Parameters
alpha

The relative time to set the animation to, 0 meaning the start, 1 meaning the end.

update_mobjects(dt: float) → None

Updates things like starting_mobject, and (for Transforms) target_mobject. Note, since typically (always?) self.mobject will have its updating suspended during the animation, this will do nothing to self.mobject.

ChangingDecimal

持续变化的数字动画:每次显示当前 ValueTracker 的值,配合 updater 可做实时计数。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "ChangingDecimal"; }

参数

decimal_mob

—,DecimalNumber

number_update_func

—,Callable[[float], float]

suspend_mobject_updating

False,bool

快速上手

number.add_updater(lambda d: d.set_value(tracker.get_value()))

API 文档

class manim.ChangingDecimal(mobject=None, *args, use_override=True, **kwargs)

基类:Animation

Animate a DecimalNumber to values specified by a user-supplied function.

Parameters

decimal_mob

The DecimalNumber instance to animate.

number_update_func

A function that returns the number to display at each point in the animation.

suspend_mobject_updating

If True, the mobject is not updated outside this animation.

Raises

TypeError

If decimal_mob is not an instance of DecimalNumber.

Examples

class ChangingDecimalExample(Scene):
    def construct(self):
        number = DecimalNumber(0)
        self.add(number)
        self.play(
            ChangingDecimal(
                number,
                lambda a: 5 * a,
                run_time=3
            )
        )
        self.wait()
interpolate_mobject(alpha: float) → None

Interpolates the mobject of the Animation based on alpha value.

Parameters
alpha

A float between 0 and 1 expressing the ratio to which the animation is completed. For example, alpha-values of 0, 0.5, and 1 correspond to the animation being completed 0%, 50%, and 100%, respectively.

Circumscribe

在 Mobject 周围画一个强调框(矩形或圆角),默认黄色,用于「注意这里」。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "AnimationGroup"; "AnimationGroup" -> "Succession"; "Succession" -> "Circumscribe"; }

参数

mobject

—,Mobject

shape

<class 'manim.mobject.geome…

fade_in

False,bool

fade_out

False,bool

time_width

0.3,float

buff

0.1,float

color

ManimColor('#FFFF00'),ParsableManimColor

run_time

1,float

stroke_width

4,float

快速上手

self.play(Circumscribe(formula))

API 文档

class manim.Circumscribe(mobject=None, *args, use_override=True, **kwargs)

基类:Succession

Draw a temporary line surrounding the mobject.

Parameters

mobject

The mobject to be circumscribed.

shape

The shape with which to surround the given mobject. Should be either Rectangle or Circle

fade_in

Whether to make the surrounding shape to fade in. It will be drawn otherwise.

fade_out

Whether to make the surrounding shape to fade out. It will be undrawn otherwise.

time_width

The time_width of the drawing and undrawing. Gets ignored if either fade_in or fade_out is True.

buff

The distance between the surrounding shape and the given mobject.

color

The color of the surrounding shape.

run_time

The duration of the entire animation.

kwargs

Additional arguments to be passed to the Succession constructor

Examples

class UsingCircumscribe(Scene):
    def construct(self):
        lbl = Tex(r"Circum-\\scribe").scale(2)
        self.add(lbl)
        self.play(Circumscribe(lbl))
        self.play(Circumscribe(lbl, Circle))
        self.play(Circumscribe(lbl, fade_out=True))
        self.play(Circumscribe(lbl, time_width=2))
        self.play(Circumscribe(lbl, Circle, True))

ClockwiseTransform

ReplacementTransform 的顺时针变体:路径按顺时针方向插值,适合旋转感的形态变化。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "Transform"; "Transform" -> "ClockwiseTransform"; }

参数

mobject

—,Mobject

target_mobject

—,Mobject

path_arc

-3.141592653589793,float

API 文档

class manim.ClockwiseTransform(mobject=None, *args, use_override=True, **kwargs)

基类:Transform

Transforms the points of a mobject along a clockwise oriented arc.

See also

Transform, CounterclockwiseTransform

Examples

class ClockwiseExample(Scene):
    def construct(self):
        dl, dr = Dot(), Dot()
        sl, sr = Square(), Square()

        VGroup(dl, sl).arrange(DOWN).shift(2*LEFT)
        VGroup(dr, sr).arrange(DOWN).shift(2*RIGHT)

        self.add(dl, dr)
        self.wait()
        self.play(
            ClockwiseTransform(dl, sl),
            Transform(dr, sr)
        )
        self.wait()

ComplexHomotopy

复同伦动画:随 t 从 0 到 1 把复平面连续变形,复分析可视化的利器。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "Homotopy"; "Homotopy" -> "ComplexHomotopy"; }

参数

complex_homotopy

—

mobject

—,Mobject

API 文档

class manim.ComplexHomotopy(mobject=None, *args, use_override=True, **kwargs)

基类:Homotopy

CounterclockwiseTransform

ReplacementTransform 的逆时针变体,与 ClockwiseTransform 对应。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "Transform"; "Transform" -> "CounterclockwiseTransform"; }

参数

mobject

—,Mobject

target_mobject

—,Mobject

path_arc

3.141592653589793,float

API 文档

class manim.CounterclockwiseTransform(mobject=None, *args, use_override=True, **kwargs)

基类:Transform

Transforms the points of a mobject along a counterclockwise oriented arc.

See also

Transform, ClockwiseTransform

Examples

class CounterclockwiseTransform_vs_Transform(Scene):
    def construct(self):
        # set up the numbers
        c_transform = VGroup(DecimalNumber(number=3.141, num_decimal_places=3), DecimalNumber(number=1.618, num_decimal_places=3))
        text_1 = Text("CounterclockwiseTransform", color=RED)
        c_transform.add(text_1)

        transform = VGroup(DecimalNumber(number=1.618, num_decimal_places=3), DecimalNumber(number=3.141, num_decimal_places=3))
        text_2 = Text("Transform", color=BLUE)
        transform.add(text_2)

        ints = VGroup(c_transform, transform)
        texts = VGroup(text_1, text_2).scale(0.75)
        c_transform.arrange(direction=UP, buff=1)
        transform.arrange(direction=UP, buff=1)

        ints.arrange(buff=2)
        self.add(ints, texts)

        # The mobs move in clockwise direction for ClockwiseTransform()
        self.play(CounterclockwiseTransform(c_transform[0], c_transform[1]))

        # The mobs move straight up for Transform()
        self.play(Transform(transform[0], transform[1]))

Create

沿路径绘出 VMobject 的「一笔画」动画,是 ShowPartial 的便捷封装。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "ShowPartial"; "ShowPartial" -> "Create"; }

参数

mobject

—

lag_ratio

1.0,float

introducer

True,bool

快速上手

self.play(Create(circle))

API 文档

class manim.Create(mobject=None, *args, use_override=True, **kwargs)

基类:ShowPartial

Incrementally show a VMobject.

Parameters

mobject

The VMobject to animate.

Raises

TypeError

If mobject is not an instance of VMobject.

Examples

class CreateScene(Scene):
    def construct(self):
        self.play(Create(Square()))

See Also

ShowPassingFlash

CyclicReplace

把一组 Mobject 沿环置换:A 移到 B 的位置、B 移到 C……最后回到 A,可循环往复。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "Transform"; "Transform" -> "CyclicReplace"; }

参数

快速上手

self.play(CyclicReplace(a, b, c))

API 文档

class manim.CyclicReplace(mobject=None, *args, use_override=True, **kwargs)

基类:Transform

An animation moving mobjects cyclically.

In particular, this means: the first mobject takes the place of the second mobject, the second one takes the place of the third mobject, and so on. The last mobject takes the place of the first one.

Parameters

mobjects

List of mobjects to be transformed.

path_arc

The angle of the arc (in radians) that the mobjects will follow to reach their target.

kwargs

Further keyword arguments that are passed to Transform.

Examples

class CyclicReplaceExample(Scene):
    def construct(self):
        group = VGroup(Square(), Circle(), Triangle(), Star())
        group.arrange(RIGHT)
        self.add(group)

        for _ in range(4):
            self.play(CyclicReplace(*group))

DrawBorderThenFill

先描边再填充的两段式入场动画,兼具 Create 和 FadeIn 的效果,适合大面积图形。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "DrawBorderThenFill"; }

参数

vmobject

—

run_time

2,float

rate_func

<function double_smooth at …,Callable[[float], float]

stroke_width

2,float

stroke_color

None,str

introducer

True,bool

快速上手

self.play(DrawBorderThenFill(polygon))

API 文档

class manim.DrawBorderThenFill(mobject=None, *args, use_override=True, **kwargs)

基类:Animation

Draw the border first and then show the fill.

Examples

class ShowDrawBorderThenFill(Scene):
    def construct(self):
        self.play(DrawBorderThenFill(Square(fill_opacity=1, fill_color=ORANGE)))
begin() → None

Begin the animation.

This method is called right as an animation is being played. As much initialization as possible, especially any mobject copying, should live in this method.

get_all_mobjects() → Sequence[Mobject]

Get all mobjects involved in the animation.

Ordering must match the ordering of arguments to interpolate_submobject

Returns
Sequence[Mobject]

The sequence of mobjects.

FadeIn

淡入动画。可指定 shift、scale、target_position,让对象从某处「长」进画面,是最常用的入场方式。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "Transform"; "Transform" -> "FadeIn"; }

快速上手

self.play(FadeIn(mob, shift=UP))

API 文档

class manim.FadeIn(mobject=None, *args, use_override=True, **kwargs)

基类:_Fade

Fade in Mobject s.

Parameters

mobjects

The mobjects to be faded in.

shift

The vector by which the mobject shifts while being faded in.

target_position

The position from which the mobject starts while being faded in. In case another mobject is given as target position, its center is used.

scale

The factor by which the mobject is scaled initially before being rescaling to its original size while being faded in.

Examples

class FadeInExample(Scene):
    def construct(self):
        dot = Dot(UP * 2 + LEFT)
        self.add(dot)
        tex = Tex(
            "FadeIn with ", "shift ", r" or target\_position", " and scale"
        ).scale(1)
        animations = [
            FadeIn(tex[0]),
            FadeIn(tex[1], shift=DOWN),
            FadeIn(tex[2], target_position=dot),
            FadeIn(tex[3], scale=1.5),
        ]
        self.play(AnimationGroup(*animations, lag_ratio=0.5))

FadeOut

淡出动画,出场首选;常配合 target_position 让对象朝某个点消散。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "Transform"; "Transform" -> "FadeOut"; }

快速上手

self.play(FadeOut(mob))

API 文档

class manim.FadeOut(mobject=None, *args, use_override=True, **kwargs)

基类:_Fade

Fade out Mobject s.

Parameters

mobjects

The mobjects to be faded out.

shift

The vector by which the mobject shifts while being faded out.

target_position

The position to which the mobject moves while being faded out. In case another mobject is given as target position, its center is used.

scale

The factor by which the mobject is scaled while being faded out.

Examples

class FadeOutExample(Scene):
    def construct(self):
        dot = Dot(UP * 2 + LEFT)
        self.add(dot)
        tex = Tex(
            "FadeOut with ", "shift ", r" or target\_position", " and scale"
        ).scale(1)
        animations = [
            FadeOut(tex[0]),
            FadeOut(tex[1], shift=DOWN),
            FadeOut(tex[2], target_position=dot),
            FadeOut(tex[3], scale=0.5),
        ]
        self.play(AnimationGroup(*animations, lag_ratio=0.5))
clean_up_from_scene(scene: Scene) → None

Clean up the Scene after finishing the animation.

This includes to remove() the Animation's Mobject if the animation is a remover.

Parameters
scene

The scene the animation should be cleaned up from.

FadeToColor

平滑地把 Mobject 颜色过渡到目标色,set_color 的动画版。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "Transform"; "Transform" -> "ApplyMethod"; "ApplyMethod" -> "FadeToColor"; }

参数

mobject

—,Mobject

color

—,str

快速上手

self.play(FadeToColor(circle, RED))

API 文档

class manim.FadeToColor(mobject=None, *args, use_override=True, **kwargs)

基类:ApplyMethod

Animation that changes color of a mobject.

Examples

class FadeToColorExample(Scene):
    def construct(self):
        self.play(FadeToColor(Text("Hello World!"), color=RED))

FadeTransform

把一个 Mobject 淡出、另一个淡入并占据其位置与样式,介于替换与交叉淡化之间。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "Transform"; "Transform" -> "FadeTransform"; }

参数

mobject

—,Mobject

target_mobject

—,Mobject

stretch

True,bool

dim_to_match

1,int

API 文档

class manim.FadeTransform(mobject=None, *args, use_override=True, **kwargs)

基类:Transform

Fades one mobject into another.

Parameters

mobject

The starting Mobject.

target_mobject

The target Mobject.

stretch

Controls whether the target Mobject is stretched during the animation. Default: True.

dim_to_match

If the target mobject is not stretched automatically, this allows to adjust the initial scale of the target Mobject while it is shifted in. Setting this to 0, 1, and 2, respectively, matches the length of the target with the length of the starting Mobject in x, y, and z direction, respectively.

kwargs

Further keyword arguments are passed to the parent class.

Examples

class DifferentFadeTransforms(Scene):
    def construct(self):
        starts = [Rectangle(width=4, height=1) for _ in range(3)]
        VGroup(*starts).arrange(DOWN, buff=1).shift(3*LEFT)
        targets = [Circle(fill_opacity=1).scale(0.25) for _ in range(3)]
        VGroup(*targets).arrange(DOWN, buff=1).shift(3*RIGHT)

        self.play(*[FadeIn(s) for s in starts])
        self.play(
            FadeTransform(starts[0], targets[0], stretch=True),
            FadeTransform(starts[1], targets[1], stretch=False, dim_to_match=0),
            FadeTransform(starts[2], targets[2], stretch=False, dim_to_match=1)
        )

        self.play(*[FadeOut(mobj) for mobj in self.mobjects])
begin()

Initial setup for the animation.

The mobject to which this animation is bound is a group consisting of both the starting and the ending mobject. At the start, the ending mobject replaces the starting mobject (and is completely faded). In the end, it is set to be the other way around.

clean_up_from_scene(scene)

Clean up the Scene after finishing the animation.

This includes to remove() the Animation's Mobject if the animation is a remover.

Parameters
scene

The scene the animation should be cleaned up from.

get_all_mobjects() → Sequence[Mobject]

Get all mobjects involved in the animation.

Ordering must match the ordering of arguments to interpolate_submobject

Returns
Sequence[Mobject]

The sequence of mobjects.

ghost_to(source, target)

Replaces the source by the target and sets the opacity to 0.

If the provided target has no points, and thus a location of [0, 0, 0] the source will simply fade out where it currently is.

FadeTransformPieces

FadeTransform 的逐子对象版本:按子对象配对交叉淡化,适合家族整体换形。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "Transform"; "Transform" -> "FadeTransform"; "FadeTransform" -> "FadeTransformPieces"; }

参数

mobject

—,Mobject

target_mobject

—,Mobject

stretch

True,bool

dim_to_match

1,int

API 文档

class manim.FadeTransformPieces(mobject=None, *args, use_override=True, **kwargs)

基类:FadeTransform

Fades submobjects of one mobject into submobjects of another one.

See also

FadeTransform

Examples

class FadeTransformSubmobjects(Scene):
    def construct(self):
        src = VGroup(Square(), Circle().shift(LEFT + UP))
        src.shift(3*LEFT + 2*UP)
        src_copy = src.copy().shift(4*DOWN)

        target = VGroup(Circle(), Triangle().shift(RIGHT + DOWN))
        target.shift(3*RIGHT + 2*UP)
        target_copy = target.copy().shift(4*DOWN)

        self.play(FadeIn(src), FadeIn(src_copy))
        self.play(
            FadeTransform(src, target),
            FadeTransformPieces(src_copy, target_copy)
        )
        self.play(*[FadeOut(mobj) for mobj in self.mobjects])
begin()

Initial setup for the animation.

The mobject to which this animation is bound is a group consisting of both the starting and the ending mobject. At the start, the ending mobject replaces the starting mobject (and is completely faded). In the end, it is set to be the other way around.

ghost_to(source, target)

Replaces the source submobjects by the target submobjects and sets the opacity to 0.

Flash

在点或 Mobject 上打出一圈闪光线条的强调动画,视觉焦点效果强。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "AnimationGroup"; "AnimationGroup" -> "Flash"; }

参数

point

—,Point3DLike | Mobject

line_length

0.2,float

num_lines

12,int

flash_radius

0.1,float

line_stroke_width

3,int

color

ManimColor('#FFFF00'),ParsableManimColor

time_width

1,float

run_time

1.0,float

快速上手

self.play(Flash(point))

API 文档

class manim.Flash(mobject=None, *args, use_override=True, **kwargs)

基类:AnimationGroup

Send out lines in all directions.

Parameters

point

The center of the flash lines. If it is a Mobject its center will be used.

line_length

The length of the flash lines.

num_lines

The number of flash lines.

flash_radius

The distance from point at which the flash lines start.

line_stroke_width

The stroke width of the flash lines.

color

The color of the flash lines.

time_width

The time width used for the flash lines. See ShowPassingFlash for more details.

run_time

The duration of the animation.

kwargs

Additional arguments to be passed to the Succession constructor

Examples

class UsingFlash(Scene):
    def construct(self):
        dot = Dot(color=PURE_YELLOW).shift(DOWN)
        self.add(Tex("Flash the dot below:"), dot)
        self.play(Flash(dot))
        self.wait()
class FlashOnCircle(Scene):
    def construct(self):
        radius = 2
        circle = Circle(radius)
        self.add(circle)
        self.play(Flash(
            circle, line_length=1,
            num_lines=30, color=RED,
            flash_radius=radius+SMALL_BUFF,
            time_width=0.3, run_time=2,
            rate_func = rush_from
        ))

FocusOn

暗化全屏、用光圈聚焦目标点的提示动画,讲解时引导视线。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "Transform"; "Transform" -> "FocusOn"; }

参数

focus_point

—,Point3DLike | Mobject

opacity

0.2,float

color

ManimColor('#888888'),ParsableManimColor

run_time

2,float

快速上手

self.play(FocusOn(dot))

API 文档

class manim.FocusOn(mobject=None, *args, use_override=True, **kwargs)

基类:Transform

Shrink a spotlight to a position.

Parameters

focus_point

The point at which to shrink the spotlight. If it is a Mobject its center will be used.

opacity

The opacity of the spotlight.

color

The color of the spotlight.

run_time

The duration of the animation.

Examples

class UsingFocusOn(Scene):
    def construct(self):
        dot = Dot(color=PURE_YELLOW).shift(DOWN)
        self.add(Tex("Focusing on the dot below:"), dot)
        self.play(FocusOn(dot))
        self.wait()

GrowArrow

让 Arrow 沿自身方向从头生长出来的动画。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "Transform"; "Transform" -> "GrowFromPoint"; "GrowFromPoint" -> "GrowArrow"; }

参数

arrow

—,Arrow

point_color

None

快速上手

self.play(GrowArrow(arrow))

API 文档

class manim.GrowArrow(mobject=None, *args, use_override=True, **kwargs)

基类:GrowFromPoint

Introduce an Arrow by growing it from its start toward its tip.

Parameters

arrow

The arrow to be introduced.

point_color

Initial color of the arrow before growing to its full size. Leave empty to match arrow's color.

Examples

class GrowArrowExample(Scene):
    def construct(self):
        arrows = [Arrow(2 * LEFT, 2 * RIGHT), Arrow(2 * DR, 2 * UL)]
        VGroup(*arrows).set_x(0).arrange(buff=2)
        self.play(GrowArrow(arrows[0]))
        self.play(GrowArrow(arrows[1], point_color=RED))

GrowFromCenter

从中心向外长大的入场动画,可用于任意 Mobject。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "Transform"; "Transform" -> "GrowFromPoint"; "GrowFromPoint" -> "GrowFromCenter"; }

参数

mobject

—,Mobject

point_color

None

快速上手

self.play(GrowFromCenter(square))

API 文档

class manim.GrowFromCenter(mobject=None, *args, use_override=True, **kwargs)

基类:GrowFromPoint

Introduce an Mobject by growing it from its center.

Parameters

mobject

The mobjects to be introduced.

point_color

Initial color of the mobject before growing to its full size. Leave empty to match mobject's color.

Examples

class GrowFromCenterExample(Scene):
    def construct(self):
        squares = [Square() for _ in range(2)]
        VGroup(*squares).set_x(0).arrange(buff=2)
        self.play(GrowFromCenter(squares[0]))
        self.play(GrowFromCenter(squares[1], point_color=RED))

GrowFromEdge

从指定边缘向对侧生长的入场动画。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "Transform"; "Transform" -> "GrowFromPoint"; "GrowFromPoint" -> "GrowFromEdge"; }

参数

mobject

—,Mobject

edge

—,Vector3DLike

point_color

None

快速上手

self.play(GrowFromEdge(dot, LEFT))

API 文档

class manim.GrowFromEdge(mobject=None, *args, use_override=True, **kwargs)

基类:GrowFromPoint

Introduce an Mobject by growing it from one of its bounding box edges.

Parameters

mobject

The mobjects to be introduced.

edge

The direction to seek bounding box edge of mobject.

point_color

Initial color of the mobject before growing to its full size. Leave empty to match mobject's color.

Examples

class GrowFromEdgeExample(Scene):
    def construct(self):
        squares = [Square() for _ in range(4)]
        VGroup(*squares).set_x(0).arrange(buff=1)
        self.play(GrowFromEdge(squares[0], DOWN))
        self.play(GrowFromEdge(squares[1], RIGHT))
        self.play(GrowFromEdge(squares[2], UR))
        self.play(GrowFromEdge(squares[3], UP, point_color=RED))

GrowFromPoint

从指定点向外长大的入场动画,配合 Flash 效果极佳。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "Transform"; "Transform" -> "GrowFromPoint"; }

参数

mobject

—,Mobject

point

—,Point3DLike

point_color

None

快速上手

self.play(GrowFromPoint(mob, origin))

API 文档

class manim.GrowFromPoint(mobject=None, *args, use_override=True, **kwargs)

基类:Transform

Introduce an Mobject by growing it from a point.

Parameters

mobject

The mobjects to be introduced.

point

The point from which the mobject grows.

point_color

Initial color of the mobject before growing to its full size. Leave empty to match mobject's color.

Examples

class GrowFromPointExample(Scene):
    def construct(self):
        dot = Dot(3 * UR, color=GREEN)
        squares = [Square() for _ in range(4)]
        VGroup(*squares).set_x(0).arrange(buff=1)
        self.add(dot)
        self.play(GrowFromPoint(squares[0], ORIGIN))
        self.play(GrowFromPoint(squares[1], [-2, 2, 0]))
        self.play(GrowFromPoint(squares[2], [3, -2, 0], RED))
        self.play(GrowFromPoint(squares[3], dot, dot.get_color()))

Homotopy

同伦动画:传入关于 (x, y, z, t) 的函数,把对象连续形变到目标姿态。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "Homotopy"; }

参数

homotopy

—

mobject

—,Mobject

run_time

3,float

apply_function_kwargs

None,dict[str, Any] | None

快速上手

self.play(Homotopy(lambda x, y, z, t: (x, y + t, z), mob))

API 文档

class manim.Homotopy(mobject=None, *args, use_override=True, **kwargs)

基类:Animation

A Homotopy.

This is an animation transforming the points of a mobject according to the specified transformation function. With the parameter \(t\) moving from 0 to 1 throughout the animation and \((x, y, z)\) describing the coordinates of the point of a mobject, the function passed to the homotopy keyword argument should transform the tuple \((x, y, z, t)\) to \((x', y', z')\), the coordinates the original point is transformed to at time \(t\).

Parameters

homotopy

A function mapping \((x, y, z, t)\) to \((x', y', z')\).

mobject

The mobject transformed under the given homotopy.

run_time

The run time of the animation.

apply_function_kwargs

Keyword arguments propagated to Mobject.apply_function().

kwargs

Further keyword arguments passed to the parent class.

Examples

class HomotopyExample(Scene):
    def construct(self):
        square = Square()

        def homotopy(x, y, z, t):
            if t <= 0.25:
                progress = t / 0.25
                return (x, y + progress * 0.2 * np.sin(x), z)
            else:
                wave_progress = (t - 0.25) / 0.75
                return (x, y + 0.2 * np.sin(x + 10 * wave_progress), z)

        self.play(Homotopy(homotopy, square, rate_func= linear, run_time=2))

Indicate

轻推一下目标对象(放大再回弹)的提示动画,比 Circumscribe 更含蓄。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "Transform"; "Transform" -> "Indicate"; }

参数

mobject

—,Mobject

scale_factor

1.2,float

color

ManimColor('#FFFF00'),ParsableManimColor

rate_func

<function there_and_back at…,RateFunction

快速上手

self.play(Indicate(formula))

API 文档

class manim.Indicate(mobject=None, *args, use_override=True, **kwargs)

基类:Transform

Indicate a Mobject by temporarily resizing and recoloring it.

Parameters

mobject

The mobject to indicate.

scale_factor

The factor by which the mobject will be temporally scaled

color

The color the mobject temporally takes.

rate_func

The function defining the animation progress at every point in time.

kwargs

Additional arguments to be passed to the Succession constructor

Examples

class UsingIndicate(Scene):
    def construct(self):
        tex = Tex("Indicate").scale(3)
        self.play(Indicate(tex))
        self.wait()

LaggedStart

让一组动画按固定间隔依次启动,start_lag_ratio 控制节奏,是排队式动效的基石。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "AnimationGroup"; "AnimationGroup" -> "LaggedStart"; }

参数

快速上手

self.play(LaggedStart(*[FadeIn(m) for m in group]))

API 文档

class manim.LaggedStart(mobject=None, *args, use_override=True, **kwargs)

基类:AnimationGroup

Adjusts the timing of a series of Animation according to lag_ratio.

Parameters

animations

Sequence of Animation objects to be played.

lag_ratio

Defines the delay after which the animation is applied to submobjects. A lag_ratio of n.nn means the next animation will play when nnn% of the current animation has played. Defaults to 0.05, meaning that the next animation will begin when 5% of the current animation has played.

This does not influence the total runtime of the animation. Instead the runtime of individual animations is adjusted so that the complete animation has the defined run time.

Examples

class LaggedStartExample(Scene):
    def construct(self):
        title = Text("lag_ratio = 0.25").to_edge(UP)

        dot1 = Dot(point=LEFT * 2 + UP, radius=0.16)
        dot2 = Dot(point=LEFT * 2, radius=0.16)
        dot3 = Dot(point=LEFT * 2 + DOWN, radius=0.16)
        line_25 = DashedLine(
            start=LEFT + UP * 2,
            end=LEFT + DOWN * 2,
            color=RED
        )
        label = Text("25%", font_size=24).next_to(line_25, UP)
        self.add(title, dot1, dot2, dot3, line_25, label)

        self.play(LaggedStart(
            dot1.animate.shift(RIGHT * 4),
            dot2.animate.shift(RIGHT * 4),
            dot3.animate.shift(RIGHT * 4),
            lag_ratio=0.25,
            run_time=4
        ))

LaggedStartMap

LaggedStart 的函数式版本:对一组对象统一套用同一种动画并按序启动。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "AnimationGroup"; "AnimationGroup" -> "LaggedStart"; "LaggedStart" -> "LaggedStartMap"; }

参数

animation_class

—,type[Animation]

mobject

—,Mobject

arg_creator

None

run_time

2,float

lag_ratio

0.05,float

快速上手

self.play(LaggedStartMap(FadeIn, group, lag_ratio=0.1))

API 文档

class manim.LaggedStartMap(mobject=None, *args, use_override=True, **kwargs)

基类:LaggedStart

Plays a series of Animation while mapping a function to submobjects.

Parameters

animation_class

Animation to apply to mobject.

mobject

Mobject whose submobjects the animation, and optionally the function, are to be applied.

arg_creator

Function which will be applied to Mobject.

run_time

The duration of the animation in seconds.

lag_ratio

Defines the delay after which the animation is applied to submobjects. A lag_ratio of n.nn means the next animation will play when nnn% of the current animation has played. Defaults to 0.05, meaning that the next animation will begin when 5% of the current animation has played.

This does not influence the total runtime of the animation. Instead the runtime of individual animations is adjusted so that the complete animation has the defined run time.

kwargs

Further keyword arguments that are passed to animation_class.

Examples

class LaggedStartMapExample(Scene):
    def construct(self):
        title = Tex("LaggedStartMap").to_edge(UP, buff=LARGE_BUFF)
        dots = VGroup(
            *[Dot(radius=0.16) for _ in range(35)]
            ).arrange_in_grid(rows=5, cols=7, buff=MED_LARGE_BUFF)
        self.add(dots, title)

        # Animate yellow ripple effect
        for mob in dots, title:
            self.play(LaggedStartMap(
                ApplyMethod, mob,
                lambda m : (m.set_color, YELLOW),
                lag_ratio = 0.1,
                rate_func = there_and_back,
                run_time = 2
            ))

MaintainPositionRelativeTo

让 Mobject 在目标对象动画期间保持相对位置,常配合 ApplyFunction 锁定局部位移。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "MaintainPositionRelativeTo"; }

参数

mobject

—,Mobject

tracked_mobject

—,Mobject

API 文档

class manim.MaintainPositionRelativeTo(mobject=None, *args, use_override=True, **kwargs)

基类:Animation

interpolate_mobject(alpha: float) → None

Interpolates the mobject of the Animation based on alpha value.

Parameters

alpha

A float between 0 and 1 expressing the ratio to which the animation is completed. For example, alpha-values of 0, 0.5, and 1 correspond to the animation being completed 0%, 50%, and 100%, respectively.

MoveAlongPath

让 Mobject 沿给定路径(曲线)运动的动画。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "MoveAlongPath"; }

参数

mobject

—,Mobject

path

—,VMobject

suspend_mobject_updating

False,bool

快速上手

self.play(MoveAlongPath(dot, circle))

API 文档

class manim.MoveAlongPath(mobject=None, *args, use_override=True, **kwargs)

基类:Animation

Make one mobject move along the path of another mobject.

class MoveAlongPathExample(Scene):
    def construct(self):
        d1 = Dot().set_color(ORANGE)
        l1 = Line(LEFT, RIGHT)
        l2 = VMobject()
        self.add(d1, l1, l2)
        l2.add_updater(lambda x: x.become(Line(LEFT, d1.get_center()).set_color(ORANGE)))
        self.play(MoveAlongPath(d1, l1), rate_func=linear)
interpolate_mobject(alpha: float) → None

Interpolates the mobject of the Animation based on alpha value.

Parameters

alpha

A float between 0 and 1 expressing the ratio to which the animation is completed. For example, alpha-values of 0, 0.5, and 1 correspond to the animation being completed 0%, 50%, and 100%, respectively.

MoveToTarget

把 Mobject 移动到其 save_state 的快照位置,与 mob.target / generate_target 配合使用。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "Transform"; "Transform" -> "MoveToTarget"; }

参数

快速上手

mob.generate_target()
mob.target.shift(RIGHT)
self.play(MoveToTarget(mob))

API 文档

class manim.MoveToTarget(mobject=None, *args, use_override=True, **kwargs)

基类:Transform

Transforms a mobject to the mobject stored in its target attribute.

After calling the generate_target() method, the target attribute of the mobject is populated with a copy of it. After modifying the attribute, playing the MoveToTarget animation transforms the original mobject into the modified one stored in the target attribute.

Examples

class MoveToTargetExample(Scene):
    def construct(self):
        c = Circle()

        c.generate_target()
        c.target.set_fill(color=GREEN, opacity=0.5)
        c.target.shift(2*RIGHT + UP).scale(0.5)

        self.add(c)
        self.play(MoveToTarget(c))

PhaseFlow

对向量场(如微分方程相图)随时间演化做形变动画,动力系统可视化工具。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "PhaseFlow"; }

参数

function

—

mobject

—,Mobject

virtual_time

1,float

suspend_mobject_updating

False,bool

rate_func

<function linear at 0x7f4ff…,RateFunction

API 文档

class manim.PhaseFlow(mobject=None, *args, use_override=True, **kwargs)

基类:Animation

interpolate_mobject(alpha: float) → None

Interpolates the mobject of the Animation based on alpha value.

Parameters

alpha

A float between 0 and 1 expressing the ratio to which the animation is completed. For example, alpha-values of 0, 0.5, and 1 correspond to the animation being completed 0%, 50%, and 100%, respectively.

RemoveTextLetterByLetter

AddTextLetterByLetter 的反向动画:Text 逐字母消失。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "ShowIncreasingSubsets"; "ShowIncreasingSubsets" -> "AddTextLetterByLetter"; "AddTextLetterByLetter" -> "RemoveTextLetterByLetter"; }

参数

text

—,Text

suspend_mobject_updating

False,bool

int_func

<ufunc 'ceil'>

rate_func

<function linear at 0x7f4ff…,Callable[[float], float]

time_per_char

0.1,float

run_time

None,float | None

reverse_rate_function

True

introducer

False

remover

True

API 文档

class manim.RemoveTextLetterByLetter(mobject=None, *args, use_override=True, **kwargs)

基类:AddTextLetterByLetter

Remove a Text letter by letter from the scene.

Parameters

time_per_char

Frequency of appearance of the letters.

小技巧

This is currently only possible for class:~.Text and not for class:~.MathTex

ReplacementTransform

把一个 Mobject 原位变形替换为另一个,是最强的「变形」动画,两个对象会融合。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "Transform"; "Transform" -> "ReplacementTransform"; }

参数

mobject

—,Mobject

target_mobject

—,Mobject

快速上手

self.play(ReplacementTransform(square, circle))

API 文档

class manim.ReplacementTransform(mobject=None, *args, use_override=True, **kwargs)

基类:Transform

Replaces and morphs a mobject into a target mobject.

Parameters

mobject

The starting Mobject.

target_mobject

The target Mobject.

kwargs

Further keyword arguments that are passed to Transform.

Examples

class ReplacementTransformOrTransform(Scene):
    def construct(self):
        # set up the numbers
        r_transform = VGroup(*[Integer(i) for i in range(1,4)])
        text_1 = Text("ReplacementTransform", color=RED)
        r_transform.add(text_1)

        transform = VGroup(*[Integer(i) for i in range(4,7)])
        text_2 = Text("Transform", color=BLUE)
        transform.add(text_2)

        ints = VGroup(r_transform, transform)
        texts = VGroup(text_1, text_2).scale(0.75)
        r_transform.arrange(direction=UP, buff=1)
        transform.arrange(direction=UP, buff=1)

        ints.arrange(buff=2)
        self.add(ints, texts)

        # The mobs replace each other and none are left behind
        self.play(ReplacementTransform(r_transform[0], r_transform[1]))
        self.play(ReplacementTransform(r_transform[1], r_transform[2]))

        # The mobs linger after the Transform()
        self.play(Transform(transform[0], transform[1]))
        self.play(Transform(transform[1], transform[2]))
        self.wait()

Restore

让 Mobject 回到 save_state() 保存的状态,常用于「变了再变回去」。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "Transform"; "Transform" -> "ApplyMethod"; "ApplyMethod" -> "Restore"; }

参数

快速上手

self.play(Restore(mob))

API 文档

class manim.Restore(mobject=None, *args, use_override=True, **kwargs)

基类:ApplyMethod

Transforms a mobject to its last saved state.

To save the state of a mobject, use the save_state() method.

Examples

class RestoreExample(Scene):
    def construct(self):
        s = Square()
        s.save_state()
        self.play(FadeIn(s))
        self.play(s.animate.set_color(PURPLE).set_opacity(0.5).shift(2*LEFT).scale(3))
        self.play(s.animate.shift(5*DOWN).rotate(PI/4))
        self.wait()
        self.play(Restore(s), run_time=2)

Rotate

绕指定点旋转对象的动画,angle 为正逆时针。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "Transform"; "Transform" -> "Rotate"; }

参数

mobject

—,Mobject

angle

3.141592653589793,float

axis

array([0., 0., 1.]),Vector3DLike

about_point

None,Point3DLike | None

about_edge

None,Vector3DLike | None

快速上手

self.play(Rotate(square, PI / 2))

API 文档

class manim.Rotate(mobject=None, *args, use_override=True, **kwargs)

基类:Transform

Animation that rotates a Mobject.

Parameters

mobject

The mobject to be rotated.

angle

The rotation angle.

axis

The rotation axis as a numpy vector.

about_point

The rotation center.

about_edge

If about_point is None, this argument specifies the direction of the bounding box point to be taken as the rotation center.

Examples

class UsingRotate(Scene):
    def construct(self):
        self.play(
            Rotate(
                Square(side_length=0.5).shift(UP * 2),
                angle=2*PI,
                about_point=ORIGIN,
                rate_func=linear,
            ),
            Rotate(Square(side_length=0.5), angle=2*PI, rate_func=linear),
            )

See also

Rotating, rotate()

Rotating

持续旋转动画:不占用场景时间推进的「边转边讲」,常用于旋转对称演示。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "Rotating"; }

参数

mobject

—,Mobject

angle

6.283185307179586,float

axis

array([0., 0., 1.]),Vector3DLike

about_point

None,Point3DLike | None

about_edge

None,Vector3DLike | None

run_time

5,float

rate_func

<function linear at 0x7f4ff…,Callable[[float], float]

快速上手

self.add(Rotating(square))

API 文档

class manim.Rotating(mobject=None, *args, use_override=True, **kwargs)

基类:Animation

Animation that rotates a Mobject.

Parameters

mobject

The mobject to be rotated.

angle

The rotation angle in radians. Predefined constants such as DEGREES can also be used to specify the angle in degrees.

axis

The rotation axis as a numpy vector.

about_point

The rotation center.

about_edge

If about_point is None, this argument specifies the direction of the bounding box point to be taken as the rotation center.

run_time

The duration of the animation in seconds.

rate_func

The function defining the animation progress based on the relative runtime (see rate_functions) .

**kwargs

Additional keyword arguments passed to Animation.

Examples

class RotatingDemo(Scene):
    def construct(self):
        circle = Circle(radius=1, color=BLUE)
        line = Line(start=ORIGIN, end=RIGHT)
        arrow = Arrow(start=ORIGIN, end=RIGHT, buff=0, color=GOLD)
        vg = VGroup(circle,line,arrow)
        self.add(vg)
        anim_kw = {"about_point": arrow.get_start(), "run_time": 1}
        self.play(Rotating(arrow, 180*DEGREES, **anim_kw))
        self.play(Rotating(arrow, PI, **anim_kw))
        self.play(Rotating(vg, PI, about_point=RIGHT))
        self.play(Rotating(vg, PI, axis=UP, about_point=ORIGIN))
        self.play(Rotating(vg, PI, axis=RIGHT, about_edge=UP))
        self.play(vg.animate.move_to(ORIGIN))
class RotatingDifferentAxis(ThreeDScene):
    def construct(self):
        axes = ThreeDAxes()
        cube = Cube()
        arrow2d = Arrow(start=[0, -1.2, 1], end=[0, 1.2, 1], color=YELLOW_E)
        cube_group = VGroup(cube,arrow2d)
        self.set_camera_orientation(gamma=0, phi=40*DEGREES, theta=40*DEGREES)
        self.add(axes, cube_group)
        play_kw = {"run_time": 1.5}
        self.play(Rotating(cube_group, PI), **play_kw)
        self.play(Rotating(cube_group, PI, axis=UP), **play_kw)
        self.play(Rotating(cube_group, 180*DEGREES, axis=RIGHT), **play_kw)
        self.wait(0.5)

See also

Rotate, rotate()

interpolate_mobject(alpha: float) → None

Interpolates the mobject of the Animation based on alpha value.

Parameters
alpha

A float between 0 and 1 expressing the ratio to which the animation is completed. For example, alpha-values of 0, 0.5, and 1 correspond to the animation being completed 0%, 50%, and 100%, respectively.

ScaleInPlace

原地缩放的强调动画,set(width=...) 类的动画版本。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "Transform"; "Transform" -> "ApplyMethod"; "ApplyMethod" -> "ScaleInPlace"; }

参数

mobject

—,Mobject

scale_factor

—,float

快速上手

self.play(ScaleInPlace(circle, 1.5))

API 文档

class manim.ScaleInPlace(mobject=None, *args, use_override=True, **kwargs)

基类:ApplyMethod

Animation that scales a mobject by a certain factor.

Examples

class ScaleInPlaceExample(Scene):
    def construct(self):
        self.play(ScaleInPlace(Text("Hello World!"), 2))

ShowIncreasingSubsets

让 VGroup 的子对象逐个显示,适合逐步揭示列表或矩阵元素。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "ShowIncreasingSubsets"; }

参数

group

—,Mobject

suspend_mobject_updating

False,bool

int_func

<ufunc 'floor'>

reverse_rate_function

False

快速上手

self.play(ShowIncreasingSubsets(group))

API 文档

class manim.ShowIncreasingSubsets(mobject=None, *args, use_override=True, **kwargs)

基类:Animation

Show one submobject at a time, leaving all previous ones displayed on screen.

Examples

class ShowIncreasingSubsetsScene(Scene):
    def construct(self):
        p = VGroup(Dot(), Square(), Triangle())
        self.add(p)
        self.play(ShowIncreasingSubsets(p))
        self.wait()
interpolate_mobject(alpha: float) → None

Interpolates the mobject of the Animation based on alpha value.

Parameters
alpha

A float between 0 and 1 expressing the ratio to which the animation is completed. For example, alpha-values of 0, 0.5, and 1 correspond to the animation being completed 0%, 50%, and 100%, respectively.

ShowPartial

按进度显示路径片段的底层动画,Create 与 Uncreate 的父类,可自定义绘制方向。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "ShowPartial"; }

参数

API 文档

class manim.ShowPartial(mobject=None, *args, use_override=True, **kwargs)

基类:Animation

Abstract class for Animations that show the VMobject partially.

Raises

TypeError

If mobject is not an instance of VMobject.

See Also

Create, ShowPassingFlash

ShowPassingFlash

一道亮斑沿路径扫过的「电流」效果动画,time_width 控制亮斑宽度。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "ShowPartial"; "ShowPartial" -> "ShowPassingFlash"; }

参数

mobject

—,VMobject

time_width

0.1,float

快速上手

self.play(ShowPassingFlash(line))

API 文档

class manim.ShowPassingFlash(mobject=None, *args, use_override=True, **kwargs)

基类:ShowPartial

Show only a sliver of the VMobject each frame.

Parameters

mobject

The mobject whose stroke is animated.

time_width

The length of the sliver relative to the length of the stroke.

Examples

class TimeWidthValues(Scene):
    def construct(self):
        p = RegularPolygon(5, color=DARK_GRAY, stroke_width=6).scale(3)
        lbl = VMobject()
        self.add(p, lbl)
        p = p.copy().set_color(BLUE)
        for time_width in [0.2, 0.5, 1, 2]:
            lbl.become(Tex(r"\texttt{time\_width={{%.1f}}}"%time_width))
            self.play(ShowPassingFlash(
                p.copy().set_color(BLUE),
                run_time=2,
                time_width=time_width
            ))

See Also

Create

clean_up_from_scene(scene: Scene) → None

Clean up the Scene after finishing the animation.

This includes to remove() the Animation's Mobject if the animation is a remover.

Parameters
scene

The scene the animation should be cleaned up from.

ShowPassingFlashWithThinningStrokeWidth

ShowPassingFlash 的变体:扫过时笔画由粗变细,更像真实书写。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "AnimationGroup"; "AnimationGroup" -> "ShowPassingFlashWithThinningStrokeWidth"; }

参数

vmobject

—,VMobject

n_segments

10,int

time_width

0.1,float

remover

True,bool

API 文档

class manim.ShowPassingFlashWithThinningStrokeWidth(mobject=None, *args, use_override=True, **kwargs)

基类:AnimationGroup

ShowSubmobjectsOneByOne

把 VGroup 子对象按个显示后再按个移除的序列动画,适合对比展示。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "ShowIncreasingSubsets"; "ShowIncreasingSubsets" -> "ShowSubmobjectsOneByOne"; }

参数

group

—,Iterable[Mobject]

int_func

<ufunc 'ceil'>

快速上手

self.play(ShowSubmobjectsOneByOne(group))

API 文档

class manim.ShowSubmobjectsOneByOne(mobject=None, *args, use_override=True, **kwargs)

基类:ShowIncreasingSubsets

Show one submobject at a time, removing all previously displayed ones from screen.

ShrinkToCenter

向中心收缩消失的出场动画,FadeOut 的动感替代。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "Transform"; "Transform" -> "ApplyMethod"; "ApplyMethod" -> "ScaleInPlace"; "ScaleInPlace" -> "ShrinkToCenter"; }

参数

快速上手

self.play(ShrinkToCenter(mob))

API 文档

class manim.ShrinkToCenter(mobject=None, *args, use_override=True, **kwargs)

基类:ScaleInPlace

Animation that makes a mobject shrink to center.

Examples

class ShrinkToCenterExample(Scene):
    def construct(self):
        self.play(ShrinkToCenter(Text("Hello World!")))

SmoothedVectorizedHomotopy

Homotopy 的平滑变体:在变换中保持向量场曲线平滑,减少锯齿。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "Homotopy"; "Homotopy" -> "SmoothedVectorizedHomotopy"; }

参数

homotopy

—

mobject

—,Mobject

run_time

3,float

apply_function_kwargs

None,dict[str, Any] | None

API 文档

class manim.SmoothedVectorizedHomotopy(mobject=None, *args, use_override=True, **kwargs)

基类:Homotopy

SpinInFromNothing

一边旋转一边淡入的复合入场动画。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "Transform"; "Transform" -> "GrowFromPoint"; "GrowFromPoint" -> "GrowFromCenter"; "GrowFromCenter" -> "SpinInFromNothing"; }

参数

mobject

—,Mobject

angle

1.5707963267948966,float

point_color

None

快速上手

self.play(SpinInFromNothing(mob))

API 文档

class manim.SpinInFromNothing(mobject=None, *args, use_override=True, **kwargs)

基类:GrowFromCenter

Introduce an Mobject spinning and growing it from its center.

Parameters

mobject

The mobjects to be introduced.

angle

The amount of spinning before mobject reaches its full size. E.g. 2*PI means that the object will do one full spin before being fully introduced.

point_color

Initial color of the mobject before growing to its full size. Leave empty to match mobject's color.

Examples

class SpinInFromNothingExample(Scene):
    def construct(self):
        squares = [Square() for _ in range(3)]
        VGroup(*squares).set_x(0).arrange(buff=2)
        self.play(SpinInFromNothing(squares[0]))
        self.play(SpinInFromNothing(squares[1], angle=2 * PI))
        self.play(SpinInFromNothing(squares[2], point_color=RED))

SpiralIn

让一组子对象沿螺旋轨迹飞入的编排动画,开场集合类内容很出彩。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "SpiralIn"; }

参数

shapes

—,Mobject

scale_factor

8,float

fade_in_fraction

0.3

快速上手

self.play(SpiralIn(group))

API 文档

class manim.SpiralIn(mobject=None, *args, use_override=True, **kwargs)

基类:Animation

Create the Mobject with sub-Mobjects flying in on spiral trajectories.

Parameters

shapes

The Mobject on which to be operated.

scale_factor

The factor used for scaling the effect.

fade_in_fraction

Fractional duration of initial fade-in of sub-Mobjects as they fly inward.

Examples

class SpiralInExample(Scene):
    def construct(self):
        pi = MathTex(r"\pi").scale(7)
        pi.shift(2.25 * LEFT + 1.5 * UP)
        circle = Circle(color=GREEN_C, fill_opacity=1).shift(LEFT)
        square = Square(color=BLUE_D, fill_opacity=1).shift(UP)
        shapes = VGroup(pi, circle, square)
        self.play(SpiralIn(shapes))
interpolate_mobject(alpha: float) → None

Interpolates the mobject of the Animation based on alpha value.

Parameters
alpha

A float between 0 and 1 expressing the ratio to which the animation is completed. For example, alpha-values of 0, 0.5, and 1 correspond to the animation being completed 0%, 50%, and 100%, respectively.

Succession

把多个动画严格串成一条时间线依次播放,前一个播完才播下一个。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "AnimationGroup"; "AnimationGroup" -> "Succession"; }

参数

快速上手

self.play(Succession(FadeIn(a), FadeOut(a)))

API 文档

class manim.Succession(mobject=None, *args, use_override=True, **kwargs)

基类:AnimationGroup

Plays a series of animations in succession.

Parameters

animations

Sequence of Animation objects to be played.

lag_ratio

Defines the delay after which the animation is applied to submobjects. A lag_ratio of n.nn means the next animation will play when nnn% of the current animation has played. Defaults to 1.0, meaning that the next animation will begin when 100% of the current animation has played.

This does not influence the total runtime of the animation. Instead the runtime of individual animations is adjusted so that the complete animation has the defined run time.

Examples

class SuccessionExample(Scene):
    def construct(self):
        dot1 = Dot(point=LEFT * 2 + UP * 2, radius=0.16, color=BLUE)
        dot2 = Dot(point=LEFT * 2 + DOWN * 2, radius=0.16, color=MAROON)
        dot3 = Dot(point=RIGHT * 2 + DOWN * 2, radius=0.16, color=GREEN)
        dot4 = Dot(point=RIGHT * 2 + UP * 2, radius=0.16, color=YELLOW)
        self.add(dot1, dot2, dot3, dot4)

        self.play(Succession(
            dot1.animate.move_to(dot2),
            dot2.animate.move_to(dot3),
            dot3.animate.move_to(dot4),
            dot4.animate.move_to(dot1)
        ))
begin() → None

Begin the animation.

This method is called right as an animation is being played. As much initialization as possible, especially any mobject copying, should live in this method.

finish() → None

Finish the animation.

This method gets called when the animation is over.

interpolate(alpha: float) → None

Set the animation progress.

This method gets called for every frame during an animation.

Parameters
alpha

The relative time to set the animation to, 0 meaning the start, 1 meaning the end.

next_animation() → None

Proceeds to the next animation.

This method is called right when the active animation finishes.

update_mobjects(dt: float) → None

Updates things like starting_mobject, and (for Transforms) target_mobject. Note, since typically (always?) self.mobject will have its updating suspended during the animation, this will do nothing to self.mobject.

Swap

让两个 Mobject 交换位置的动画,常带交叉路径。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "Transform"; "Transform" -> "CyclicReplace"; "CyclicReplace" -> "Swap"; }

参数

API 文档

class manim.Swap(mobject=None, *args, use_override=True, **kwargs)

基类:CyclicReplace

Another name for CyclicReplace, which is more understandable for two entries.

Examples

class SwapExample(Scene):
    def construct(self):
        text_a = Text("A").move_to(LEFT)
        text_b = Text("B").move_to(RIGHT)
        text_group = Group(text_a, text_b)
        self.play(FadeIn(text_group))
        self.play(Swap(text_group))
        self.wait()

TracedPath

持续记录某点运动轨迹并实时绘出的「画笔」对象,配 MoveAlongPath 做轨迹可视化。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Mobject" -> "VMobject"; "VMobject" -> "TracedPath"; }

参数

traced_point_func

—,Callable

stroke_width

2,float

stroke_color

ManimColor('#FFFFFF')

dissipating_time

None,float | None

快速上手

trace = TracedPath(dot.get_center)
self.add(trace)
self.play(MoveAlongPath(dot, circle))

API 文档

class manim.TracedPath(traced_point_func: Callable, stroke_width: float = 2, stroke_color: ManimColor | int | str | NDArray[int64] | tuple[int, int, int] | NDArray[float64] | tuple[float, float, float] | tuple[int, int, int, int] | tuple[float, float, float, float] | None = ManimColor('#FFFFFF'), dissipating_time: float | None = None, **kwargs: Any)

基类:VMobject

Traces the path of a point returned by a function call.

Parameters

traced_point_func

The function to be traced.

stroke_width

The width of the trace.

stroke_color

The color of the trace.

dissipating_time

The time taken for the path to dissipate. Default set to None which disables dissipation.

Examples

class TracedPathExample(Scene):
    def construct(self):
        circ = Circle(color=RED).shift(4*LEFT)
        dot = Dot(color=RED).move_to(circ.get_start())
        rolling_circle = VGroup(circ, dot)
        trace = TracedPath(circ.get_start)
        rolling_circle.add_updater(lambda m: m.rotate(-0.3))
        self.add(trace, rolling_circle)
        self.play(rolling_circle.animate.shift(8*RIGHT), run_time=4, rate_func=linear)
class DissipatingPathExample(Scene):
    def construct(self):
        a = Dot(RIGHT * 2)
        b = TracedPath(a.get_center, dissipating_time=0.5, stroke_opacity=[0, 1])
        self.add(a, b)
        self.play(a.animate(path_arc=PI / 4).shift(LEFT * 2))
        self.play(a.animate(path_arc=-PI / 4).shift(LEFT * 2))
        self.wait()

Transform

把一个 Mobject 平滑变形为另一个的标准变换动画,所有 Transform 家族的基类。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "Transform"; }

参数

mobject

—,Mobject | None

target_mobject

None,Mobject | None

path_func

None,Callable | None

path_arc

0,float

path_arc_axis

array([0., 0., 1.]),np.ndarray

path_arc_centers

None

replace_mobject_with_target_in_scene

False,bool

快速上手

self.play(Transform(square, circle))

API 文档

class manim.Transform(mobject=None, *args, use_override=True, **kwargs)

基类:Animation

A Transform transforms a Mobject into a target Mobject.

Parameters

mobject

The Mobject to be transformed. It will be mutated to become the target_mobject.

target_mobject

The target of the transformation.

path_func

A function defining the path that the points of the mobject are being moved along until they match the points of the target_mobject, see utils.paths.

path_arc

The arc angle (in radians) that the points of mobject will follow to reach the points of the target if using a circular path arc, see path_arc_centers. See also manim.utils.paths.path_along_arc().

path_arc_axis

The axis to rotate along if using a circular path arc, see path_arc_centers.

path_arc_centers

The center of the circular arcs along which the points of mobject are moved by the transformation.

If this is set and path_func is not set, then a path_along_circles path will be generated using the path_arc parameters and stored in path_func. If path_func is set, this and the other path_arc fields are set as attributes, but a path_func is not generated from it.

replace_mobject_with_target_in_scene

Controls which mobject is replaced when the transformation is complete.

If set to True, mobject will be removed from the scene and target_mobject will replace it. Otherwise, target_mobject is never added and mobject just takes its shape.

Examples

class TransformPathArc(Scene):
    def construct(self):
        def make_arc_path(start, end, arc_angle):
            points = []
            p_fn = path_along_arc(arc_angle)
            # alpha animates between 0.0 and 1.0, where 0.0
            # is the beginning of the animation and 1.0 is the end.
            for alpha in range(0, 11):
                points.append(p_fn(start, end, alpha / 10.0))
            path = VMobject(stroke_color=YELLOW)
            path.set_points_smoothly(points)
            return path

        left = Circle(stroke_color=BLUE_E, fill_opacity=1.0, radius=0.5).move_to(LEFT * 2)
        colors = [TEAL_A, TEAL_B, TEAL_C, TEAL_D, TEAL_E, GREEN_A]
        # Positive angles move counter-clockwise, negative angles move clockwise.
        examples = [-90, 0, 30, 90, 180, 270]
        anims = []
        for idx, angle in enumerate(examples):
            left_c = left.copy().shift((3 - idx) * UP)
            left_c.fill_color = colors[idx]
            right_c = left_c.copy().shift(4 * RIGHT)
            path_arc = make_arc_path(left_c.get_center(), right_c.get_center(),
                                     arc_angle=angle * DEGREES)
            desc = Text('%d°' % examples[idx]).next_to(left_c, LEFT)
            # Make the circles in front of the text in front of the arcs.
            self.add(
                path_arc.set_z_index(1),
                desc.set_z_index(2),
                left_c.set_z_index(3),
            )
            anims.append(Transform(left_c, right_c, path_arc=angle * DEGREES))

        self.play(*anims, run_time=2)
        self.wait()

See also

ReplacementTransform, interpolate(), align_data()

begin() → None

Begin the animation.

This method is called right as an animation is being played. As much initialization as possible, especially any mobject copying, should live in this method.

clean_up_from_scene(scene: Scene) → None

Clean up the Scene after finishing the animation.

This includes to remove() the Animation's Mobject if the animation is a remover.

Parameters
scene

The scene the animation should be cleaned up from.

get_all_mobjects() → Sequence[Mobject]

Get all mobjects involved in the animation.

Ordering must match the ordering of arguments to interpolate_submobject

Returns
Sequence[Mobject]

The sequence of mobjects.

TransformAnimations

把两个动画「对齐」:让第一个动画的结尾状态匹配第二个动画的起点,实现无缝衔接。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "Transform"; "Transform" -> "TransformAnimations"; }

参数

start_anim

—,Animation

end_anim

—,Animation

rate_func

<function squish_rate_func.…,Callable

API 文档

class manim.TransformAnimations(mobject=None, *args, use_override=True, **kwargs)

基类:Transform

interpolate(alpha: float) → None

Set the animation progress.

This method gets called for every frame during an animation.

Parameters

alpha

The relative time to set the animation to, 0 meaning the start, 1 meaning the end.

TransformFromCopy

先复制出副本再变形到位的动画,原对象保留,强调「由它推导」的逻辑。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "Transform"; "Transform" -> "TransformFromCopy"; }

参数

mobject

—,Mobject

target_mobject

—,Mobject

快速上手

self.play(TransformFromCopy(a, b))

API 文档

class manim.TransformFromCopy(mobject=None, *args, use_override=True, **kwargs)

基类:Transform

Preserves a copy of the original VMobject and transforms only it's copy to the target VMobject

interpolate(alpha: float) → None

Set the animation progress.

This method gets called for every frame during an animation.

Parameters

alpha

The relative time to set the animation to, 0 meaning the start, 1 meaning the end.

TransformMatchingShapes

按形状相似度在两个 VGroup 间自动配对子对象逐一变形,重构公式、图形的神器。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "AnimationGroup"; "AnimationGroup" -> "TransformMatchingShapes"; }

参数

mobject

—,Mobject

target_mobject

—,Mobject

transform_mismatches

False,bool

fade_transform_mismatches

False,bool

key_map

None,dict | None

快速上手

self.play(TransformMatchingShapes(vg1, vg2))

API 文档

class manim.TransformMatchingShapes(mobject=None, *args, use_override=True, **kwargs)

基类:TransformMatchingAbstractBase

An animation trying to transform groups by matching the shape of their submobjects.

Two submobjects match if the hash of their point coordinates after normalization (i.e., after translation to the origin, fixing the submobject height at 1 unit, and rounding the coordinates to three decimal places) matches.

See also

TransformMatchingAbstractBase

Examples

class Anagram(Scene):
    def construct(self):
        src = Text("the morse code")
        tar = Text("here come dots")
        self.play(Write(src))
        self.wait(0.5)
        self.play(TransformMatchingShapes(src, tar, path_arc=PI/2))
        self.wait(0.5)

TransformMatchingTex

TransformMatchingShapes 的 Tex 特化:按 LaTeX 片段配对变形,公式演算的标配。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "AnimationGroup"; "AnimationGroup" -> "TransformMatchingTex"; }

参数

mobject

—,Mobject

target_mobject

—,Mobject

transform_mismatches

False,bool

fade_transform_mismatches

False,bool

key_map

None,dict | None

快速上手

self.play(TransformMatchingTex(eq1, eq2))

API 文档

class manim.TransformMatchingTex(mobject=None, *args, use_override=True, **kwargs)

基类:TransformMatchingAbstractBase

A transformation trying to transform rendered LaTeX strings.

Two submobjects match if their tex_string matches.

See also

TransformMatchingAbstractBase

Examples

class MatchingEquationParts(Scene):
    def construct(self):
        variables = VGroup(MathTex("a"), MathTex("b"), MathTex("c")).arrange_submobjects().shift(UP)

        eq1 = MathTex("{{x}}^2", "+", "{{y}}^2", "=", "{{z}}^2")
        eq2 = MathTex("{{a}}^2", "+", "{{b}}^2", "=", "{{c}}^2")
        eq3 = MathTex("{{a}}^2", "=", "{{c}}^2", "-", "{{b}}^2")

        self.add(eq1)
        self.wait(0.5)
        self.play(TransformMatchingTex(Group(eq1, variables), eq2))
        self.wait(0.5)
        self.play(TransformMatchingTex(eq2, eq3))
        self.wait(0.5)

TypeWithCursor

打字机动画 + 闪烁光标:Text 逐字输入,末尾跟一个可自定义的光标 Mobject。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "ShowIncreasingSubsets"; "ShowIncreasingSubsets" -> "AddTextLetterByLetter"; "AddTextLetterByLetter" -> "TypeWithCursor"; }

参数

text

—,Text

cursor

—,Mobject

buff

0.1,float

keep_cursor_y

True,bool

leave_cursor_on

True,bool

time_per_char

0.1,float

reverse_rate_function

False

introducer

True

快速上手

self.play(TypeWithCursor(text, cursor))

API 文档

class manim.TypeWithCursor(mobject=None, *args, use_override=True, **kwargs)

基类:AddTextLetterByLetter

Similar to AddTextLetterByLetter , but with an additional cursor mobject at the end.

Parameters

time_per_char

Frequency of appearance of the letters.

cursor

Mobject shown after the last added letter.

buff

Controls how far away the cursor is to the right of the last added letter.

keep_cursor_y

If True, the cursor's y-coordinate is set to the center of the Text and remains the same throughout the animation. Otherwise, it is set to the center of the last added letter.

leave_cursor_on

Whether to show the cursor after the animation.

小技巧

This is currently only possible for class:~.Text and not for class:~.MathTex.

Examples

class InsertingTextExample(Scene):
    def construct(self):
        text = Text("Inserting", color=PURPLE).scale(1.5).to_edge(LEFT)
        cursor = Rectangle(
            color = GREY_A,
            fill_color = GREY_A,
            fill_opacity = 1.0,
            height = 1.1,
            width = 0.5,
        ).move_to(text[0]) # Position the cursor

        self.play(TypeWithCursor(text, cursor))
        self.play(Blink(cursor, blinks=2))
begin() → None

Begin the animation.

This method is called right as an animation is being played. As much initialization as possible, especially any mobject copying, should live in this method.

clean_up_from_scene(scene: Scene) → None

Clean up the Scene after finishing the animation.

This includes to remove() the Animation's Mobject if the animation is a remover.

Parameters
scene

The scene the animation should be cleaned up from.

finish() → None

Finish the animation.

This method gets called when the animation is over.

Uncreate

Create 的反向动画:沿路径把图形擦除。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "ShowPartial"; "ShowPartial" -> "Create"; "Create" -> "Uncreate"; }

参数

mobject

—

reverse_rate_function

True,bool

remover

True,bool

快速上手

self.play(Uncreate(circle))

API 文档

class manim.Uncreate(mobject=None, *args, use_override=True, **kwargs)

基类:Create

Like Create but in reverse.

Examples

class ShowUncreate(Scene):
    def construct(self):
        self.play(Uncreate(Square()))

See Also

Create

UntypeWithCursor

TypeWithCursor 的反向动画:带光标逐字删除文本。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "ShowIncreasingSubsets"; "ShowIncreasingSubsets" -> "AddTextLetterByLetter"; "AddTextLetterByLetter" -> "TypeWithCursor"; "TypeWithCursor" -> "UntypeWithCursor"; }

参数

text

—,Text

cursor

None,VMobject | None

time_per_char

0.1,float

reverse_rate_function

True

introducer

False

remover

True

API 文档

class manim.UntypeWithCursor(mobject=None, *args, use_override=True, **kwargs)

基类:TypeWithCursor

Similar to RemoveTextLetterByLetter , but with an additional cursor mobject at the end.

Parameters

time_per_char

Frequency of appearance of the letters.

cursor

Mobject shown after the last added letter.

buff

Controls how far away the cursor is to the right of the last added letter.

keep_cursor_y

If True, the cursor's y-coordinate is set to the center of the Text and remains the same throughout the animation. Otherwise, it is set to the center of the last added letter.

leave_cursor_on

Whether to show the cursor after the animation.

小技巧

This is currently only possible for class:~.Text and not for class:~.MathTex.

Examples

class DeletingTextExample(Scene):
    def construct(self):
        text = Text("Deleting", color=PURPLE).scale(1.5).to_edge(LEFT)
        cursor = Rectangle(
            color = GREY_A,
            fill_color = GREY_A,
            fill_opacity = 1.0,
            height = 1.1,
            width = 0.5,
        ).move_to(text[0]) # Position the cursor

        self.play(UntypeWithCursor(text, cursor))
        self.play(Blink(cursor, blinks=2))

Unwrite

Write 的反向动画:按书写顺序把文本或公式擦除。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "DrawBorderThenFill"; "DrawBorderThenFill" -> "Write"; "Write" -> "Unwrite"; }

参数

vmobject

—,VMobject

rate_func

<function linear at 0x7f4ff…,Callable[[float], float]

reverse

True,bool

快速上手

self.play(Unwrite(text))

API 文档

class manim.Unwrite(mobject=None, *args, use_override=True, **kwargs)

基类:Write

Simulate erasing by hand a Text or a VMobject.

Parameters

reverse

Set True to have the animation start erasing from the last submobject first.

Examples

class UnwriteReverseTrue(Scene):
    def construct(self):
        text = Tex("Alice and Bob").scale(3)
        self.add(text)
        self.play(Unwrite(text))
class UnwriteReverseFalse(Scene):
    def construct(self):
        text = Tex("Alice and Bob").scale(3)
        self.add(text)
        self.play(Unwrite(text, reverse=False))

UpdateFromAlphaFunc

用 updater 按动画进度 alpha 驱动任意更新逻辑的自定义动画骨架。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "UpdateFromFunc"; "UpdateFromFunc" -> "UpdateFromAlphaFunc"; }

参数

mobject

—,Mobject

update_function

—,Callable[[Mobject], Any]

suspend_mobject_updating

False,bool

API 文档

class manim.UpdateFromAlphaFunc(mobject=None, *args, use_override=True, **kwargs)

基类:UpdateFromFunc

interpolate_mobject(alpha: float) → None

Interpolates the mobject of the Animation based on alpha value.

Parameters

alpha

A float between 0 and 1 expressing the ratio to which the animation is completed. For example, alpha-values of 0, 0.5, and 1 correspond to the animation being completed 0%, 50%, and 100%, respectively.

UpdateFromFunc

在动画时长内对目标持续应用更新函数的自定义动画,适合「边播边算」的场景。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "UpdateFromFunc"; }

参数

mobject

—,Mobject

update_function

—,Callable[[Mobject], Any]

suspend_mobject_updating

False,bool

API 文档

class manim.UpdateFromFunc(mobject=None, *args, use_override=True, **kwargs)

基类:Animation

update_function of the form func(mobject), presumably to be used when the state of one mobject is dependent on another simultaneously animated mobject

interpolate_mobject(alpha: float) → None

Interpolates the mobject of the Animation based on alpha value.

Parameters

alpha

A float between 0 and 1 expressing the ratio to which the animation is completed. For example, alpha-values of 0, 0.5, and 1 correspond to the animation being completed 0%, 50%, and 100%, respectively.

Wait

停顿动画:让时间流逝 nothing 发生(或跑背景动画),self.wait() 的动画版。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "Wait"; }

参数

run_time

1,float

stop_condition

None

frozen_frame

None,bool | None

rate_func

<function linear at 0x7f4ff…,Callable[[float], float]

快速上手

self.play(Wait(2))

API 文档

class manim.Wait(mobject=None, *args, use_override=True, **kwargs)

基类:Animation

A "no operation" animation.

Parameters

run_time

The amount of time that should pass.

stop_condition

A function without positional arguments that evaluates to a boolean. The function is evaluated after every new frame has been rendered. Playing the animation stops after the return value is truthy, or after the specified run_time has passed.

frozen_frame

Controls whether or not the wait animation is static, i.e., corresponds to a frozen frame. If False is passed, the render loop still progresses through the animation as usual and (among other things) continues to call updater functions. If None (the default value), the Scene.play() call tries to determine whether the Wait call can be static or not itself via Scene.should_mobjects_update().

kwargs

Keyword arguments to be passed to the parent class, Animation.

begin() → None

Begin the animation.

This method is called right as an animation is being played. As much initialization as possible, especially any mobject copying, should live in this method.

clean_up_from_scene(scene: Scene) → None

Clean up the Scene after finishing the animation.

This includes to remove() the Animation's Mobject if the animation is a remover.

Parameters
scene

The scene the animation should be cleaned up from.

finish() → None

Finish the animation.

This method gets called when the animation is over.

interpolate(alpha: float) → None

Set the animation progress.

This method gets called for every frame during an animation.

Parameters
alpha

The relative time to set the animation to, 0 meaning the start, 1 meaning the end.

update_mobjects(dt: float) → None

Updates things like starting_mobject, and (for Transforms) target_mobject. Note, since typically (always?) self.mobject will have its updating suspended during the animation, this will do nothing to self.mobject.

Wiggle

让对象来回扭动摇摆的强调动画,适合标记不确定性或活跃状态。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "Wiggle"; }

参数

mobject

—,Mobject

scale_value

1.1,float

rotation_angle

0.06283185307179587,float

n_wiggles

6,int

scale_about_point

None,Point3DLike | None

rotate_about_point

None,Point3DLike | None

run_time

2,float

快速上手

self.play(Wiggle(mob))

API 文档

class manim.Wiggle(mobject=None, *args, use_override=True, **kwargs)

基类:Animation

Wiggle a Mobject.

Parameters

mobject

The mobject to wiggle.

scale_value

The factor by which the mobject will be temporarily scaled.

rotation_angle

The wiggle angle.

n_wiggles

The number of wiggles.

scale_about_point

The point about which the mobject gets scaled.

rotate_about_point

The point around which the mobject gets rotated.

run_time

The duration of the animation

Examples

class ApplyingWaves(Scene):
    def construct(self):
        tex = Tex("Wiggle").scale(3)
        self.play(Wiggle(tex))
        self.wait()

Write

按文字/笔画顺序「书写」文本的动画,Tex、Text 演算推导的标志性入场方式。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Animation" -> "DrawBorderThenFill"; "DrawBorderThenFill" -> "Write"; }

参数

vmobject

—

rate_func

<function linear at 0x7f4ff…,Callable[[float], float]

reverse

False,bool

快速上手

self.play(Write(text))

API 文档

class manim.Write(mobject=None, *args, use_override=True, **kwargs)

基类:DrawBorderThenFill

Simulate hand-writing a Text or hand-drawing a VMobject.

Examples

class ShowWrite(Scene):
    def construct(self):
        self.play(Write(Text("Hello", font_size=144)))
class ShowWriteReversed(Scene):
    def construct(self):
        self.play(Write(Text("Hello", font_size=144), reverse=True, remover=False))

Tests

Check that creating empty Write animations works:

>>> from manim import Write, Text
>>> Write(Text(''))
Write(Text(''))
begin() → None

Begin the animation.

This method is called right as an animation is being played. As much initialization as possible, especially any mobject copying, should live in this method.

finish() → None

Finish the animation.

This method gets called when the animation is over.