Learning by Example¶
SquareToCircle¶
example_scenes.py
contains simple examples that we can use to learn about manim.
Go ahead and try out the SquareToCircle
scene by running it with $ manim example_scenes.py SquareToCircle -p
in manim directory.
1 2 3 4 5 6 7 8 9 10 11 12 13 | from manimlib.imports import *
class SquareToCircle(Scene):
def construct(self):
circle = Circle()
square = Square()
square.flip(RIGHT)
square.rotate(-3 * TAU / 8)
circle.set_fill(PINK, opacity=0.5)
self.play(ShowCreation(square))
self.play(Transform(square, circle))
self.play(FadeOut(square))
|
Note
The flag -p
plays the rendered video with default video player.
Other frequently used flags are:
-l
for rendering video in lower resolution (which renders faster)-s
to show the last frame of the video.
Run manim -h
all the available flags (python -m manim -h
if you installed it to a venv)
Let’s step through each line of SquareToCircle
3 | class SquareToCircle(Scene):
|
You create videos in manim by writing Scene
classes.
Each Scene
in manim is self-contained. That means everything
you created under this scene does not exist outside the class.
4 | def construct(self):
|
construct()
specifies what is displayed on the screen
when the Scene
is rendered to video.
5 6 | circle = Circle()
square = Square()
|
Circle()
and Square()
create Circle
and Square
.
Both of these are instances of Mobject
subclasses, the base class for objects in manim. Note
that instantiating a Mobject
does not add it to the
Scene
, so you wouldn’t see anything if you were to render
the Scene
at this point.
7 8 9 | square.flip(RIGHT)
square.rotate(-3 * TAU / 8)
circle.set_fill(PINK, opacity=0.5)
|
flip()
rotate()
set_fill()
apply various modifications to the mobjects before animating
them. The call to flip()
flips the
Square
across the RIGHT vector. This is equivalent
to a refection across the x-axis.
The call to rotate()
rotates the
Square
3/8ths of a full rotation counterclockwise.
The call to set_fill()
sets
the fill color for the Circle
to pink, and its opacity to 0.5.
11 12 13 | self.play(ShowCreation(square))
self.play(Transform(square, circle))
self.play(FadeOut(square))
|
To generated animation, Animation
classes are used.
Each Animation
takes one or more Mobject
instances as arguments, which it animates
when passed to play()
. This is how video is typically
created in manim.
Mobject
instances are automatically
added to the Scene
when they are animated. You can add a
Mobject
to the Scene
manually
by passing it as an argument to add()
.
ShowCreation
draws a Mobject
to the screen.
Transform
morphs one Mobject
into another.
FadeOut
fades a Mobject
out of the Scene
.
Note
Only the first argument to Transform
is modified,
the second is not added to the Scene
. Transform
only changes the appearance but not the underlying properties.
After the call to transform()
square
is still a Square
instance
but with the shape of Circle
.