API 参考:Mobject 基类类型(types)¶
共 14 个类,按字母排序。每个类含中文说明、继承链、参数表与上手示例,API 文档由 autodoc 从 manim v0.21.0 源码自动生成;带完整中文精讲的类见 API 索引。
CurvesAsSubmobjects¶
把多段曲线拆成独立子对象的 VMobject 容器,方便对每一段单独上色或动画。
继承关系¶
参数¶
API 文档¶
- class manim.CurvesAsSubmobjects(vmobject: VMobject, **kwargs)¶
基类:
VGroupConvert a curve's elements to submobjects.
Examples¶
class LineGradientExample(Scene): def construct(self): curve = ParametricFunction(lambda t: [t, np.sin(t), 0], t_range=[-PI, PI, 0.01], stroke_width=10) new_curve = CurvesAsSubmobjects(curve) new_curve.set_color_by_gradient(BLUE, RED) self.add(new_curve.shift(UP), curve)
- point_from_proportion(alpha: float) Point3D¶
Gets the point at a proportion along the path of the
CurvesAsSubmobjects.Parameters¶
- alpha
The proportion along the the path of the
CurvesAsSubmobjects.
Returns¶
numpy.ndarrayThe point on the
CurvesAsSubmobjects.
Raises¶
ValueErrorIf
alphais not between 0 and 1.ExceptionIf the
CurvesAsSubmobjectshas no submobjects, or no submobject has points.
DashedVMobject¶
把任意 VMobject 变成虚线版:dash_length 与间距可调,常用来表示辅助线或预期位置。
继承关系¶
参数¶
|
—,VMobject |
|---|---|
|
15,int |
|
0.5,float |
|
0,float |
|
ManimColor('#FFFFFF'),ManimColor |
|
True,bool |
快速上手¶
dashed = DashedVMobject(circle)
API 文档¶
- class manim.DashedVMobject(vmobject: VMobject, num_dashes: int = 15, dashed_ratio: float = 0.5, dash_offset: float = 0, color: ManimColor = ManimColor('#FFFFFF'), equal_lengths: bool = True, **kwargs)¶
基类:
VMobjectA
VMobjectcomposed of dashes instead of lines.Parameters¶
- vmobject
The object that will get dashed
- num_dashes
Number of dashes to add.
- dashed_ratio
Ratio of dash to empty space.
- dash_offset
Shifts the starting point of dashes along the path. Value 1 shifts by one full dash length.
- equal_lengths
If
True, dashes will be (approximately) equally long. IfFalse, dashes will be split evenly in the curve's input t variable (legacy behavior).
Examples¶
class DashedVMobjectExample(Scene): def construct(self): r = 0.5 top_row = VGroup() # Increasing num_dashes for dashes in range(1, 12): circ = DashedVMobject(Circle(radius=r, color=WHITE), num_dashes=dashes) top_row.add(circ) middle_row = VGroup() # Increasing dashed_ratio for ratio in np.arange(1 / 11, 1, 1 / 11): circ = DashedVMobject( Circle(radius=r, color=WHITE), dashed_ratio=ratio ) middle_row.add(circ) func1 = FunctionGraph(lambda t: t**5,[-1,1],color=WHITE) func_even = DashedVMobject(func1,num_dashes=6,equal_lengths=True) func_stretched = DashedVMobject(func1, num_dashes=6, equal_lengths=False) bottom_row = VGroup(func_even,func_stretched) top_row.arrange(buff=0.3) middle_row.arrange() bottom_row.arrange(buff=1) everything = VGroup(top_row, middle_row, bottom_row).arrange(DOWN, buff=1) self.add(everything)
ImageMobject¶
把本地图片文件(PNG/JPG)作为 Mobject 摆进画面,可缩放、旋转、裁剪。
继承关系¶
参数¶
|
—,StrPath | npt.NDArray |
|---|---|
|
1080,int |
|
False,bool |
|
'RGBA',str |
快速上手¶
img = ImageMobject("photo.png").scale(2)
API 文档¶
- class manim.ImageMobject(filename_or_array: StrPath | npt.NDArray, scale_to_resolution: int = 1080, invert: bool = False, image_mode: str = 'RGBA', **kwargs: Any)¶
-
Displays an Image from a numpy array or a file.
Parameters¶
- scale_to_resolution
At this resolution the image is placed pixel by pixel onto the screen, so it will look the sharpest and best. This is a custom parameter of ImageMobject so that rendering a scene with e.g. the
--quality lowor--quality mediumflag for faster rendering won't effect the position of the image on the screen.
Example¶
class ImageFromArray(Scene): def construct(self): image = ImageMobject(np.uint8([[0, 100, 30, 200], [255, 0, 5, 33]])) image.height = 7 self.add(image)
Changing interpolation style:
class ImageInterpolationEx(Scene): def construct(self): img = ImageMobject(np.uint8([[63, 0, 0, 0], [0, 127, 0, 0], [0, 0, 191, 0], [0, 0, 0, 255] ])) img.height = 3 group = Group() algorithm_texts = ["nearest", "linear", "cubic"] for algorithm_text in algorithm_texts: algorithm = RESAMPLING_ALGORITHMS[algorithm_text] img_copy = img.copy().set_resampling_algorithm(algorithm) img_copy.add(Text(algorithm_text).scale(0.5).next_to(img_copy, UP)) group.add(img_copy) group.arrange() self.add(group)
- fade(darkness: float = 0.5, family: bool = True) Self¶
Sets the image's opacity using a 1 - alpha relationship.
Parameters¶
- darkness
The alpha value of the object, 1 being transparent and 0 being opaque.
- family
Whether the submobjects of the ImageMobject should be affected.
- get_pixel_array() PixelArray¶
A simple getter method.
- interpolate_color(mobject1: Mobject, mobject2: Mobject, alpha: float) Self¶
Interpolates the array of pixel color values from one ImageMobject into an array of equal size in the target ImageMobject.
Parameters¶
- mobject1
The ImageMobject to transform from.
- mobject2
The ImageMobject to transform into.
- alpha
Used to track the lerp relationship. Not opacity related.
- set_color(color: ParsableManimColor = ManimColor('#F7D96F'), alpha: Any = None, family: bool = True) Self¶
Condition is function which takes in one arguments, (x, y, z). Here it just recurses to submobjects, but in subclasses this should be further implemented based on the the inner workings of color
ImageMobjectFromCamera¶
捕获另一个相机画面作为图像的 Mobject,用于画中画或场景缩略预览。
继承关系¶
参数¶
|
—,MovingCamera |
|---|---|
|
None,dict[str, Any] | None |
API 文档¶
- class manim.ImageMobjectFromCamera(camera: MovingCamera, default_display_frame_config: dict[str, Any] | None = None, **kwargs: Any)¶
Mobject1D¶
一维对象基类(v0.21 标记为内部实验类型),普通教程较少直接使用。
继承关系¶
参数¶
API 文档¶
Mobject2D¶
二维对象基类(内部实验类型),面片类对象的祖先。
继承关系¶
参数¶
API 文档¶
PGroup¶
PMobject 的专用容器:把点集对象分组统一管理。
继承关系¶
API 文档¶
- class manim.PGroup(*pmobs: Any, **kwargs: Any)¶
基类:
PMobjectA group for several point mobjects.
Examples¶
class PgroupExample(Scene): def construct(self): p1 = PointCloudDot(radius=1, density=20, color=BLUE) p1.move_to(4.5 * LEFT) p2 = PointCloudDot() p3 = PointCloudDot(radius=1.5, stroke_width=2.5, color=PINK) p3.move_to(4.5 * RIGHT) pList = PGroup(p1, p2, p3) self.add(pList)
PMobject¶
点云式 Mobject:只含离散点、无填充笔画,是 DotCloud 等实验性渲染类型的基类。
继承关系¶
参数¶
API 文档¶
- class manim.PMobject(stroke_width: int = 4, **kwargs: Any)¶
基类:
MobjectA disc made of a cloud of Dots
Examples¶
class PMobjectExample(Scene): def construct(self): pG = PGroup() # This is just a collection of PMobject's # As the scale factor increases, the number of points # removed increases. for sf in range(1, 9 + 1): p = PointCloudDot(density=20, radius=1).thin_out(sf) # PointCloudDot is a type of PMobject # and can therefore be added to a PGroup pG.add(p) # This organizes all the shapes in a grid. pG.arrange_in_grid() self.add(pG)
- add_points(points: Point3DLike_Array, rgbas: FloatRGBALike_Array | None = None, color: ParsableManimColor | None = None, alpha: float = 1.0) Self¶
Add points.
Points must be a Nx3 numpy array. Rgbas must be a Nx4 numpy array if it is not None.
- get_color() ManimColor¶
Returns the color of the
MobjectExamples¶
>>> from manim import Square, RED >>> Square(color=RED).get_color() == RED True
- get_point_mobject(center: Point3DLike | None = None) Point¶
The simplest
Mobjectto be transformed to or from self. Should by a point of the appropriate type
- reset_points() Self¶
Sets
pointsto be an empty array.
- set_color(color: ParsableManimColor = ManimColor('#FFFF00'), family: bool = True) Self¶
Condition is function which takes in one arguments, (x, y, z). Here it just recurses to submobjects, but in subclasses this should be further implemented based on the the inner workings of color
- set_color_by_gradient(*colors: ParsableManimColor) Self¶
Parameters¶
- colors
The colors to use for the gradient. Use like set_color_by_gradient(RED, BLUE, GREEN).
self.color = ManimColor.parse(color) return self
- sort_points(function: Callable[[npt.NDArray[ManimFloat]], float] = <function PMobject.<lambda>>) Self¶
Function is any map from R^3 to R
- thin_out(factor: int = 5) Self¶
Removes all but every nth point for n = factor
Point¶
表示坐标点的轻量 Mobject:不渲染任何可见图形,只承载位置,常作动画的锚点参数。
继承关系¶
参数¶
|
array([0., 0., 0.]),Point3DLike |
|---|---|
|
ManimColor('#000000'),ManimColor |
快速上手¶
self.play(GrowFromPoint(mob, Point().get_center()))
API 文档¶
- class manim.Point(location: Point3DLike = array([0., 0., 0.]), color: ManimColor = ManimColor('#000000'), **kwargs: Any)¶
基类:
PMobjectA mobject representing a point.
Examples¶
class ExamplePoint(Scene): def construct(self): colorList = [RED, GREEN, BLUE, YELLOW] for i in range(200): point = Point(location=[0.63 * np.random.randint(-4, 4), 0.37 * np.random.randint(-4, 4), 0], color=np.random.choice(colorList)) self.add(point) for i in range(200): point = Point(location=[0.37 * np.random.randint(-4, 4), 0.63 * np.random.randint(-4, 4), 0], color=np.random.choice(colorList)) self.add(point) self.add(point)
- generate_points() Self¶
Initializes
pointsand therefore the shape.Gets called upon creation. This is an empty method that can be implemented by subclasses.
PointCloudDot¶
把点集渲染成一群小圆点的 PMobject 显示形式,适合散点可视化。
继承关系¶
参数¶
|
array([0., 0., 0.]),Point3DLike |
|---|---|
|
2.0,float |
|
2,int |
|
10,int |
|
ManimColor('#FFFF00'),ManimColor |
API 文档¶
- class manim.PointCloudDot(center: Point3DLike = array([0., 0., 0.]), radius: float = 2.0, stroke_width: int = 2, density: int = 10, color: ManimColor = ManimColor('#FFFF00'), **kwargs: Any)¶
基类:
Mobject1DA disc made of a cloud of dots.
Examples¶
class PointCloudDotExample(Scene): def construct(self): cloud_1 = PointCloudDot(color=RED) cloud_2 = PointCloudDot(stroke_width=4, radius=1) cloud_3 = PointCloudDot(density=15) group = Group(cloud_1, cloud_2, cloud_3).arrange() self.add(group)
class PointCloudDotExample2(Scene): def construct(self): plane = ComplexPlane() cloud = PointCloudDot(color=RED) self.add( plane, cloud ) self.wait() self.play( cloud.animate.apply_complex_function(lambda z: np.exp(z)) )
- generate_points() Self¶
Initializes
pointsand therefore the shape.Gets called upon creation. This is an empty method that can be implemented by subclasses.
VDict¶
「键值对版 VGroup」:按键名索引子对象,方便在公式字典里做局部替换。
继承关系¶
参数¶
|
{} |
|---|---|
|
False,bool |
快速上手¶
d = VDict({"a": MathTex("x^2"), "b": MathTex("y^2")})
API 文档¶
- class manim.VDict(mapping_or_iterable: Mapping[Hashable, VMobject] | Iterable[tuple[Hashable, VMobject]] = {}, show_keys: bool = False, **kwargs)¶
基类:
VMobjectA VGroup-like class, also offering submobject access by key, like a python dict
Parameters¶
- mapping_or_iterable
The parameter specifying the key-value mapping of keys and mobjects.
- show_keys
Whether to also display the key associated with the mobject. This might be useful when debugging, especially when there are a lot of mobjects in the
VDict. Defaults to False.- kwargs
Other arguments to be passed to Mobject.
Attributes¶
- show_keys
bool Whether to also display the key associated with the mobject. This might be useful when debugging, especially when there are a lot of mobjects in the
VDict. When displayed, the key is towards the left of the mobject. Defaults to False.- submob_dict
dict Is the actual python dictionary that is used to bind the keys to the mobjects.
Examples¶
class ShapesWithVDict(Scene): def construct(self): square = Square().set_color(RED) circle = Circle().set_color(YELLOW).next_to(square, UP) # create dict from list of tuples each having key-mobject pair pairs = [("s", square), ("c", circle)] my_dict = VDict(pairs, show_keys=True) # display it just like a VGroup self.play(Create(my_dict)) self.wait() text = Tex("Some text").set_color(GREEN).next_to(square, DOWN) # add a key-value pair by wrapping it in a single-element list of tuple # after attrs branch is merged, it will be easier like `.add(t=text)` my_dict.add([("t", text)]) self.wait() rect = Rectangle().next_to(text, DOWN) # can also do key assignment like a python dict my_dict["r"] = rect # access submobjects like a python dict my_dict["t"].set_color(PURPLE) self.play(my_dict["t"].animate.scale(3)) self.wait() # also supports python dict styled reassignment my_dict["t"] = Tex("Some other text").set_color(BLUE) self.wait() # remove submobject by key my_dict.remove("t") self.wait() self.play(Uncreate(my_dict["s"])) self.wait() self.play(FadeOut(my_dict["c"])) self.wait() self.play(FadeOut(my_dict["r"], shift=DOWN)) self.wait() # you can also make a VDict from an existing dict of mobjects plain_dict = { 1: Integer(1).shift(DOWN), 2: Integer(2).shift(2 * DOWN), 3: Integer(3).shift(3 * DOWN), } vdict_from_plain_dict = VDict(plain_dict) vdict_from_plain_dict.shift(1.5 * (UP + LEFT)) self.play(Create(vdict_from_plain_dict)) # you can even use zip vdict_using_zip = VDict(zip(["s", "c", "r"], [Square(), Circle(), Rectangle()])) vdict_using_zip.shift(1.5 * RIGHT) self.play(Create(vdict_using_zip)) self.wait()
- add(mapping_or_iterable: Mapping[Hashable, VMobject] | Iterable[tuple[Hashable, VMobject]]) Self¶
Adds the key-value pairs to the
VDictobject.Also, it internally adds the value to the submobjects
listofMobject, which is responsible for actual on-screen display.Parameters¶
- mapping_or_iterable
The parameter specifying the key-value mapping of keys and mobjects.
Returns¶
Examples¶
Normal usage:
square_obj = Square() my_dict.add([("s", square_obj)])
- add_key_value_pair(key: Hashable, value: VMobject) Self¶
A utility function used by
add()to add the key-value pair tosubmob_dict. Not really meant to be used externally.Parameters¶
- key
The key of the submobject to be added.
- value
The mobject associated with the key
Returns¶
None
Raises¶
- TypeError
If the value is not an instance of VMobject
Examples¶
Normal usage:
square_obj = Square() self.add_key_value_pair("s", square_obj)
- get_all_submobjects() list[list]¶
To get all the submobjects associated with a particular
VDictobjectReturns¶
dict_valuesAll the submobjects associated with the
VDictobject
Examples¶
Normal usage:
for submob in my_dict.get_all_submobjects(): self.play(Create(submob))
- remove(key: Hashable) Self¶
Removes the mobject from the
VDictobject having the key keyAlso, it internally removes the mobject from the submobjects
listofMobject, (which is responsible for removing it from the screen)Parameters¶
- key
The key of the submoject to be removed.
Returns¶
Examples¶
Normal usage:
my_dict.remove("square")
VGroup¶
VMobject 专用容器:子对象都是 VMobject,可使用只有矢量对象才有的整体方法(如 set_stroke),是日常最常用组合器。
继承关系¶
快速上手¶
vg = VGroup(circle, square, dot)
vg.arrange(RIGHT)
API 文档¶
- class manim.VGroup(*vmobjects: VMobject | Iterable[VMobject], **kwargs: Any)¶
基类:
VMobjectA group of vectorized mobjects.
This can be used to group multiple
VMobjectinstances together in order to scale, move, ... them together.Notes¶
When adding the same mobject more than once, repetitions are ignored. Use
Mobject.copy()to create a separate copy which can then be added to the group.Examples¶
To add
VGroup, you can either use theadd()method, or use the + and += operators. Similarly, you can subtract elements of a VGroup viaremove()method, or - and -= operators:>>> from manim import Triangle, Square, VGroup >>> vg = VGroup() >>> triangle, square = Triangle(), Square() >>> vg.add(triangle) VGroup(Triangle) >>> vg + square # a new VGroup is constructed VGroup(Triangle, Square) >>> vg # not modified VGroup(Triangle) >>> vg += square >>> vg # modifies vg VGroup(Triangle, Square) >>> vg.remove(triangle) VGroup(Square) >>> vg - square # a new VGroup is constructed VGroup() >>> vg # not modified VGroup(Square) >>> vg -= square >>> vg # modifies vg VGroup()
class ArcShapeIris(Scene): def construct(self): colors = [DARK_BROWN, BLUE_E, BLUE_D, BLUE_A, TEAL_B, GREEN_B, YELLOW_E] radius = [1 + rad * 0.1 for rad in range(len(colors))] circles_group = VGroup() # zip(radius, color) makes the iterator [(radius[i], color[i]) for i in range(radius)] circles_group.add(*[Circle(radius=rad, stroke_width=10, color=col) for rad, col in zip(radius, colors)]) self.add(circles_group)
- add(*vmobjects: VMobject | Iterable[VMobject]) Self¶
Checks if all passed elements are an instance, or iterables of VMobject and then adds them to submobjects
Parameters¶
- vmobjects
List or iterable of VMobjects to add
Returns¶
Raises¶
- TypeError
If one element of the list, or iterable is not an instance of VMobject
Examples¶
The following example shows how to add individual or multiple VMobject instances through the VGroup constructor and its .add() method.
class AddToVGroup(Scene): def construct(self): circle_red = Circle(color=RED) circle_green = Circle(color=GREEN) circle_blue = Circle(color=BLUE) circle_red.shift(LEFT) circle_blue.shift(RIGHT) gr = VGroup(circle_red, circle_green) gr2 = VGroup(circle_blue) # Constructor uses add directly self.add(gr,gr2) self.wait() gr += gr2 # Add group to another self.play( gr.animate.shift(DOWN), ) gr -= gr2 # Remove group self.play( # Animate groups separately gr.animate.shift(LEFT), gr2.animate.shift(UP), ) self.play( #Animate groups without modification (gr+gr2).animate.shift(RIGHT) ) self.play( # Animate group without component (gr-circle_red).animate.shift(RIGHT) )
A VGroup can be created using iterables as well. Keep in mind that all generated values from an iterable must be an instance of VMobject. This is demonstrated below:
class AddIterableToVGroupExample(Scene): def construct(self): v = VGroup( Square(), # Singular VMobject instance [Circle(), Triangle()], # List of VMobject instances Dot(), (Dot() for _ in range(2)), # Iterable that generates VMobjects ) v.arrange() self.add(v)
To facilitate this, the iterable is unpacked before its individual instances are added to the VGroup. As a result, when you index a VGroup, you will never get back an iterable. Instead, you will always receive VMobject instances, including those that were part of the iterable/s that you originally added to the VGroup.
VMobject¶
矢量对象基类:一切「用路径曲线定义」的图形(圆、线、文字)都继承它。set_stroke/set_fill、贝塞尔操作都从这里来。
继承关系¶
参数¶
|
None |
|---|---|
|
0.0,float |
|
None |
|
1.0,float |
|
4,float |
|
ManimColor('#000000') |
|
1.0,float |
|
0,float |
|
0.0,float |
|
None,LineJointType | None |
|
array([-1., 1., 0.]),Vector3DLike |
|
False,bool |
|
0.01,float |
|
False,bool |
|
None,Image | str | None |
|
False,bool |
|
1e-06,float |
|
4,int |
|
|
快速上手¶
vm = VMobject()
vm.set_points_as_corners([ORIGIN, RIGHT, UP])
API 文档¶
- class manim.VMobject(fill_color: ParsableManimColor | None = None, fill_opacity: float = 0.0, stroke_color: ParsableManimColor | None = None, stroke_opacity: float = 1.0, stroke_width: float = 4, background_stroke_color: ParsableManimColor | None = ManimColor('#000000'), background_stroke_opacity: float = 1.0, background_stroke_width: float = 0, sheen_factor: float = 0.0, joint_type: LineJointType | None = None, sheen_direction: Vector3DLike = array([-1., 1., 0.]), close_new_points: bool = False, pre_function_handle_to_anchor_scale_factor: float = 0.01, make_smooth_after_applying_functions: bool = False, background_image: Image | str | None = None, shade_in_3d: bool = False, tolerance_for_point_equality: float = 1e-06, n_points_per_cubic_curve: int = 4, cap_style: CapStyleType = CapStyleType.AUTO, **kwargs: Any)¶
基类:
MobjectA vectorized mobject.
Parameters¶
- background_stroke_color
The purpose of background stroke is to have something that won't overlap fill, e.g. For text against some textured background.
- sheen_factor
When a color c is set, there will be a second color computed based on interpolating c to WHITE by with sheen_factor, and the display will gradient to this secondary color in the direction of sheen_direction.
- close_new_points
Indicates that it will not be displayed, but that it should count in parent mobject's path
- tolerance_for_point_equality
This is within a pixel
- joint_type
The line joint type used to connect the curve segments of this vectorized mobject. See
LineJointTypefor options.
- add_cubic_bezier_curve_to(handle1: Point3DLike, handle2: Point3DLike, anchor: Point3DLike) Self¶
Add cubic bezier curve to the path.
NOTE : the first anchor is not a parameter as by default the end of the last sub-path!
Parameters¶
- handle1
first handle
- handle2
second handle
- anchor
anchor
Returns¶
VMobjectself
- add_line_to(point: Point3DLike) Self¶
Add a straight line from the last point of VMobject to the given point.
Parameters¶
- point
The end of the straight line.
Returns¶
VMobjectself
- add_points_as_corners(points: Point3DLike_Array) Self¶
Append multiple straight lines at the end of
VMobject.points, which connect the givenpointsin order starting from the end of the current path. Thesepointswould be therefore the corners of the new polyline appended to the path.Parameters¶
- points
An array of 3D points representing the corners of the polyline to append to
VMobject.points.
Returns¶
VMobjectThe VMobject itself, after appending the straight lines to its path.
- add_quadratic_bezier_curve_to(handle: Point3DLike, anchor: Point3DLike) Self¶
Add Quadratic bezier curve to the path.
Returns¶
VMobjectself
- add_smooth_curve_to(*points: Point3DLike) Self¶
Creates a smooth curve from given points and add it to the VMobject. If two points are passed in, the first is interpreted as a handle, the second as an anchor.
Parameters¶
- points
Points (anchor and handle, or just anchor) to add a smooth curve from
Returns¶
VMobjectself
Raises¶
- ValueError
If 0 or more than 2 points are given.
- align_points(vmobject: VMobject) Self¶
Adds points to self and vmobject so that they both have the same number of subpaths, with corresponding subpaths each containing the same number of points.
Points are added either by subdividing curves evenly along the subpath, or by creating new subpaths consisting of a single point repeated.
Parameters¶
- vmobject
The object to align points with.
Returns¶
VMobjectself
See also¶
- append_points(new_points: Point3DLike_Array) Self¶
Append the given
new_pointsto the end ofVMobject.points.Parameters¶
- new_points
An array of 3D points to append.
Returns¶
VMobjectThe VMobject itself, after appending
new_points.
- change_anchor_mode(mode: Literal['jagged', 'smooth']) Self¶
Changes the anchor mode of the bezier curves. This will modify the handles.
There can be only two modes, "jagged", and "smooth".
Returns¶
VMobjectself
- consider_points_equals_2d(p0: Point2DLike, p1: Point2DLike) bool¶
Determine if two points are close enough to be considered equal.
This uses the semantics of
numpy.isclose(), but expands the comparison for two coordinates to avoid NumPy's per-call overhead. Parameters ---------- p0first point
- p1
second point
Returns¶
- bool
whether two points considered close.
- property fill_color: ManimColor¶
If there are multiple colors (for gradient) this returns the first one
- force_direction(target_direction: Literal['CW', 'CCW']) Self¶
Makes sure that points are either directed clockwise or counterclockwise.
Parameters¶
- target_direction
Either
"CW"or"CCW".
- gen_cubic_bezier_tuples_from_points(points: CubicBezierPathLike) tuple[CubicBezierPointsLike, ...]¶
Returns the bezier tuples from an array of points.
self.points is a list of the anchors and handles of the bezier curves of the mobject (ie [anchor1, handle1, handle2, anchor2, anchor3 ..]) This algorithm basically retrieve them by taking an element every n, where n is the number of control points of the bezier curve.
Parameters¶
- points
Points from which control points will be extracted.
Returns¶
- tuple
Bezier control points.
- generate_rgbas_array(color: ParsableManimColor | Iterable[ManimColor] | None, opacity: float | Iterable[float]) FloatRGBA¶
First arg can be either a color, or a tuple/list of colors. Likewise, opacity can either be a float, or a tuple of floats. If self.sheen_factor is not zero, and only one color was passed in, a second slightly light color will automatically be added for the gradient
- get_anchors() list[Point3D]¶
Returns the anchors of the curves forming the VMobject.
Returns¶
- Point3D_Array
The anchors.
- get_anchors_and_handles() list[Point3D_Array]¶
Returns anchors1, handles1, handles2, anchors2, where (anchors1[i], handles1[i], handles2[i], anchors2[i]) will be four points defining a cubic bezier curve for any i in range(0, len(anchors1))
Returns¶
- list[Point3D_Array]
Iterable of the anchors and handles.
- get_arc_length(sample_points_per_curve: int | None = None) float¶
Return the approximated length of the whole curve.
Parameters¶
- sample_points_per_curve
Number of sample points per curve used to approximate the length. More points result in a better approximation.
Returns¶
- float
The length of the
VMobject.
- get_color() ManimColor¶
Returns the color of the
MobjectExamples¶
>>> from manim import Square, RED >>> Square(color=RED).get_color() == RED True
- get_curve_functions() Iterable[Callable[[float], Point3D]]¶
Gets the functions for the curves of the mobject.
Returns¶
- Iterable[Callable[[float], Point3D]]
The functions for the curves.
- get_curve_functions_with_lengths(**kwargs) Iterable[tuple[Callable[[float], Point3D], float]]¶
Gets the functions and lengths of the curves for the mobject.
Parameters¶
**kwargsThe keyword arguments passed to
get_nth_curve_function_with_length()
Returns¶
- Iterable[tuple[Callable[[float], Point3D], float]]
The functions and lengths of the curves.
- get_direction() Literal['CW', 'CCW']¶
Uses
shoelace_direction()to calculate the direction. The direction of points determines in which direction the object is drawn, clockwise or counterclockwise.Examples¶
The default direction of a
Circleis counterclockwise:>>> from manim import Circle >>> Circle().get_direction() 'CCW'
Returns¶
strEither
"CW"or"CCW".
- get_end_anchors() Point3D_Array¶
Return the end anchors of the bezier curves.
Returns¶
- Point3D_Array
Starting anchors
- get_fill_color() ManimColor¶
If there are multiple colors (for gradient) this returns the first one
- get_fill_opacity() ManimFloat¶
If there are multiple opacities, this returns the first
- get_nth_curve_function(n: int) Callable[[float], Point3D]¶
Returns the expression of the nth curve.
Parameters¶
- n
index of the desired curve.
Returns¶
- Callable[float, Point3D]
expression of the nth bezier curve.
- get_nth_curve_function_with_length(n: int, sample_points: int | None = None) tuple[Callable[[float], Point3D], float]¶
Returns the expression of the nth curve along with its (approximate) length.
Parameters¶
- n
The index of the desired curve.
- sample_points
The number of points to sample to find the length.
Returns¶
- curveCallable[[float], Point3D]
The function for the nth curve.
- length
float The length of the nth curve.
- get_nth_curve_length(n: int, sample_points: int | None = None) float¶
Returns the (approximate) length of the nth curve.
Parameters¶
- n
The index of the desired curve.
- sample_points
The number of points to sample to find the length.
Returns¶
- length
float The length of the nth curve.
- get_nth_curve_length_pieces(n: int, sample_points: int | None = None) npt.NDArray[ManimFloat]¶
Returns the array of short line lengths used for length approximation.
Parameters¶
- n
The index of the desired curve.
- sample_points
The number of points to sample to find the length.
Returns¶
The short length-pieces of the nth curve.
- get_nth_curve_points(n: int) CubicBezierPoints¶
Returns the points defining the nth curve of the vmobject.
Parameters¶
- n
index of the desired bezier curve.
Returns¶
- CubicBezierPoints
points defining the nth bezier curve (anchors, handles)
- get_num_curves() int¶
Returns the number of curves of the vmobject.
Returns¶
- int
number of curves of the vmobject.
- get_point_mobject(center: Point3DLike | None = None) VectorizedPoint¶
The simplest
Mobjectto be transformed to or from self. Should by a point of the appropriate type
- get_start_anchors() Point3D_Array¶
Returns the start anchors of the bezier curves.
Returns¶
- Point3D_Array
Starting anchors
- get_subcurve(a: float, b: float) Self¶
Returns the subcurve of the VMobject between the interval [a, b]. The curve is a VMobject itself.
Parameters¶
- a
The lower bound.
- b
The upper bound.
Returns¶
- VMobject
The subcurve between of [a, b]
- get_subpath_split_indices_from_points(points: CubicBezierPathLike, n_dims: int = 3) npt.NDArray[np.int_]¶
Return the point indices delimiting each subpath in
points.A subpath is a run of consecutive cubic Bézier curves where every curve's end anchor coincides with the next curve's start anchor; a split is introduced wherever two consecutive anchors differ. This is the vectorized equivalent of the comparison done by
consider_points_equals()(orconsider_points_equals_2d()whenn_dims == 2), matching their handling of non-finite coordinates (NaN/inf) as well.Parameters¶
- points
The array of points to split into subpaths.
- n_dims
The number of coordinates to compare when deciding whether two anchors coincide: 3 for the full 3D points, or 2 to consider only their
xandycoordinates. Default is 3.
Returns¶
- np.ndarray
A
(n_subpaths, 2)int array whose rows are the[start, end]point index ranges (end-exclusive) of each subpath.
- get_subpaths() list[CubicSpline]¶
Returns subpaths formed by the curves of the VMobject.
Subpaths are ranges of curves with each pair of consecutive curves having their end/start points coincident.
Returns¶
- list[CubicSpline]
subpaths.
- init_colors(propagate_colors: bool = True) Self¶
Initializes the colors.
Gets called upon creation. This is an empty method that can be implemented by subclasses.
- insert_n_curves(n: int) Self¶
Inserts n curves to the bezier curves of the vmobject.
Parameters¶
- n
Number of curves to insert.
Returns¶
VMobjectself
- insert_n_curves_to_point_list(n: int, points: BezierPathLike) BezierPath¶
Given an array of k points defining a bezier curves (anchors and handles), returns points defining exactly k + n bezier curves.
Parameters¶
- n
Number of desired curves.
- points
Starting points.
Returns¶
Points generated.
- point_from_proportion(alpha: float) Point3D¶
Gets the point at a proportion along the path of the
VMobject.Parameters¶
- alpha
The proportion along the the path of the
VMobject.
Returns¶
numpy.ndarrayThe point on the
VMobject.
Raises¶
ValueErrorIf
alphais not between 0 and 1.ExceptionIf the
VMobjecthas no points.
Example¶
class PointFromProportion(Scene): def construct(self): line = Line(2*DL, 2*UR) self.add(line) colors = (RED, BLUE, YELLOW) proportions = (1/4, 1/2, 3/4) for color, proportion in zip(colors, proportions): self.add(Dot(color=color).move_to( line.point_from_proportion(proportion) ))
- pointwise_become_partial(vmobject: VMobject, a: float, b: float) Self¶
Given a 2nd
VMobjectvmobject, a lower boundaand an upper boundb, modify thisVMobject's points to match the portion of the Bézier spline described byvmobject.pointswith the parametertbetweenaandb.Parameters¶
- vmobject
The
VMobjectthat will serve as a model.- a
The lower bound for
t.- b
The upper bound for
t
Returns¶
Raises¶
- TypeError
If
vmobjectis not an instance ofVMobject.
- proportion_from_point(point: Point3DLike) float¶
Returns the proportion along the path of the
VMobjecta particular given point is at.Parameters¶
- point
The Cartesian coordinates of the point which may or may not lie on the
VMobject
Returns¶
- float
The proportion along the path of the
VMobject.
Raises¶
ValueErrorIf
pointdoes not lie on the curve.ExceptionIf the
VMobjecthas no points.
- resize_points(new_length: int, resize_func: Callable[[Point3D_Array, int], Point3D_Array] = <function resize_array>) Self¶
Resize the array of anchor points and handles to have the specified size.
Parameters¶
- new_length
The new (total) number of points.
- resize_func
A function mapping a Numpy array (the points) and an integer (the target size) to a Numpy array. The default implementation is based on Numpy's
resizefunction.
- reverse_direction() Self¶
Reverts the point direction by inverting the point order.
Returns¶
VMobjectReturns self.
Examples¶
class ChangeOfDirection(Scene): def construct(self): ccw = RegularPolygon(5) ccw.shift(LEFT) cw = RegularPolygon(5) cw.shift(RIGHT).reverse_direction() self.play(Create(ccw), Create(cw), run_time=4)
- rotate(angle: float, axis: Vector3DLike = array([0., 0., 1.]), *, about_point: Point3DLike | None = None, about_edge: Vector3DLike | None = None) Self¶
Rotates the
Mobjectaround a specified axis and point.Parameters¶
- angle
The angle of rotation in radians. Predefined constants such as
DEGREEScan also be used to specify the angle in degrees.- axis
The rotation axis (see
Rotatingfor more).- about_point
The point about which the mobject rotates. If
None, rotation occurs around the center of the mobject.- about_edge
The edge about which to apply the scaling.
Returns¶
Mobjectself(for method chaining)
备注
To animate a rotation, use
RotatingorRotateinstead of.animate.rotate(...). The.animate.rotate(...)syntax only applies a transformation from the initial state to the final rotated state (interpolation between the two states), without showing proper rotational motion based on the angle (from 0 to the given angle).Examples¶
class RotateMethodExample(Scene): def construct(self): circle = Circle(radius=1, color=BLUE) line = Line(start=ORIGIN, end=RIGHT) arrow1 = Arrow(start=ORIGIN, end=RIGHT, buff=0, color=GOLD) group1 = VGroup(circle, line, arrow1) group2 = group1.copy() arrow2 = group2[2] arrow2.rotate(angle=PI / 4, about_point=arrow2.get_start()) group3 = group1.copy() arrow3 = group3[2] arrow3.rotate(angle=120 * DEGREES, about_point=arrow3.get_start()) self.add(VGroup(group1, group2, group3).arrange(RIGHT, buff=1))
See also¶
Rotating,Rotate,animate,apply_points_function_about_point()
- rotate_sheen_direction(angle: float, axis: Vector3DLike = array([0., 0., 1.]), family: bool = True) Self¶
Rotates the direction of the applied sheen.
Parameters¶
- angle
Angle by which the direction of sheen is rotated.
- axis
Axis of rotation.
Examples¶
Normal usage:
Circle().set_sheen_direction(UP).rotate_sheen_direction(PI)
See Also¶
- scale(scale_factor: float, scale_stroke: bool = False, *, about_point: Point3DLike | None = None, about_edge: Vector3DLike | None = None) Self¶
Scale the size by a factor.
Default behavior is to scale about the center of the vmobject.
Parameters¶
- scale_factor
The scaling factor \(\alpha\). If \(0 < |\alpha| < 1\), the mobject will shrink, and for \(|\alpha| > 1\) it will grow. Furthermore, if \(\alpha < 0\), the mobject is also flipped.
- scale_stroke
Boolean determining if each submobject's outline is scaled when the object is scaled. If enabled, each submobject keeps its relative stroke width (for example, a submobject with a 2px outline scaled by a factor of .5 will have a 1px outline, while a submobject with 0px stroke remains at 0px).
- kwargs
Additional keyword arguments passed to
scale().
Returns¶
VMobjectself
Examples¶
class MobjectScaleExample(Scene): def construct(self): c1 = Circle(1, RED).set_x(-1) c2 = Circle(1, GREEN).set_x(1) vg = VGroup(c1, c2) vg.set_stroke(width=50) self.add(vg) self.play( c1.animate.scale(.25), c2.animate.scale(.25, scale_stroke=True) )
See also¶
move_to()
- scale_handle_to_anchor_distances(factor: float) Self¶
If the distance between a given handle point H and its associated anchor point A is d, then it changes H to be a distances factor*d away from A, but so that the line from A to H doesn't change. This is mostly useful in the context of applying a (differentiable) function, to preserve tangency properties. One would pull all the handles closer to their anchors, apply the function then push them out again.
Parameters¶
- factor
The factor used for scaling.
Returns¶
VMobjectself
- set_anchors_and_handles(anchors1: Point3DLike_Array, handles1: Point3DLike_Array, handles2: Point3DLike_Array, anchors2: Point3DLike_Array) Self¶
Given two sets of anchors and handles, process them to set them as anchors and handles of the VMobject.
anchors1[i], handles1[i], handles2[i] and anchors2[i] define the i-th bezier curve of the vmobject. There are four hardcoded parameters and this is a problem as it makes the number of points per cubic curve unchangeable from 4 (two anchors and two handles).
Returns¶
VMobjectself
- set_cap_style(cap_style: CapStyleType) Self¶
Sets the cap style of the
VMobject.Parameters¶
- cap_style
The cap style to be set. See
CapStyleTypefor options.
Returns¶
VMobjectself
Examples¶
class CapStyleExample(Scene): def construct(self): line = Line(LEFT, RIGHT, color=YELLOW, stroke_width=20) line.set_cap_style(CapStyleType.ROUND) self.add(line)
- set_color(color: ParsableManimColor, family: bool = True) Self¶
Condition is function which takes in one arguments, (x, y, z). Here it just recurses to submobjects, but in subclasses this should be further implemented based on the the inner workings of color
- set_fill(color: ParsableManimColor | None = None, opacity: float | None = None, family: bool = True) Self¶
Set the fill color and fill opacity of a
VMobject.Parameters¶
Returns¶
VMobjectself
Examples¶
class SetFill(Scene): def construct(self): square = Square().scale(2).set_fill(WHITE,1) circle1 = Circle().set_fill(GREEN,0.8) circle2 = Circle().set_fill(YELLOW) # No fill_opacity circle3 = Circle().set_fill(color = '#FF2135', opacity = 0.2) group = Group(circle1,circle2,circle3).arrange() self.add(square) self.add(group)
See Also¶
set_style()
- set_points_as_corners(points: Point3DLike_Array) Self¶
Given an array of points, set them as corners of the
VMobject.To achieve that, this algorithm sets handles aligned with the anchors such that the resultant Bézier curve will be the segment between the two anchors.
Parameters¶
- points
Array of points that will be set as corners.
Returns¶
VMobjectThe VMobject itself, after setting the new points as corners.
Examples¶
class PointsAsCornersExample(Scene): def construct(self): corners = ( # create square UR, UL, DL, DR, UR, # create crosses DL, UL, DR ) vmob = VMobject(stroke_color=RED) vmob.set_points_as_corners(corners).scale(2) self.add(vmob)
- set_sheen(factor: float, direction: Vector3DLike | None = None, family: bool = True) Self¶
Applies a color gradient from a direction.
Parameters¶
- factor
The extent of lustre/gradient to apply. If negative, the gradient starts from black, if positive the gradient starts from white and changes to the current color.
- direction
Direction from where the gradient is applied.
Examples¶
class SetSheen(Scene): def construct(self): circle = Circle(fill_opacity=1).set_sheen(-0.3, DR) self.add(circle)
- set_sheen_direction(direction: Vector3DLike, family: bool = True) Self¶
Sets the direction of the applied sheen.
Parameters¶
- direction
Direction from where the gradient is applied.
Examples¶
Normal usage:
Circle().set_sheen_direction(UP)
See Also¶
- start_new_path(point: Point3DLike) Self¶
Append a
pointto theVMobject.points, which will be the beginning of a new Bézier curve in the path given by the points. If there's an unfinished curve at the end ofVMobject.points, complete it by appending the last Bézier curve's start anchor as many times as needed.Parameters¶
- point
A 3D point to append to
VMobject.points.
Returns¶
VMobjectThe VMobject itself, after appending
pointand starting a new curve.
VectorizedPoint¶
带矢量渲染能力的点对象(Point 的 VMobject 版本),内部实验用途居多。
继承关系¶
参数¶
|
array([0., 0., 0.]),Point3DLike |
|---|---|
|
ManimColor('#000000'),ManimColor |
|
0,float |
|
0,float |
|
0.01,float |
|
0.01,float |
API 文档¶
- class manim.VectorizedPoint(location: Point3DLike = array([0., 0., 0.]), color: ManimColor = ManimColor('#000000'), fill_opacity: float = 0, stroke_width: float = 0, artificial_width: float = 0.01, artificial_height: float = 0.01, **kwargs)¶
基类:
VMobject- property height: float¶
The height of the mobject.
Returns¶
floatExamples¶
class HeightExample(Scene): def construct(self): decimal = DecimalNumber().to_edge(UP) rect = Rectangle(color=BLUE) rect_copy = rect.copy().set_stroke(GRAY, opacity=0.5) decimal.add_updater(lambda d: d.set_value(rect.height)) self.add(rect_copy, rect, decimal) self.play(rect.animate.set(height=5)) self.wait()
See also¶
length_over_dim()
- property width: float¶
The width of the mobject.
Returns¶
floatExamples¶
class WidthExample(Scene): def construct(self): decimal = DecimalNumber().to_edge(UP) rect = Rectangle(color=BLUE) rect_copy = rect.copy().set_stroke(GRAY, opacity=0.5) decimal.add_updater(lambda d: d.set_value(rect.width)) self.add(rect_copy, rect, decimal) self.play(rect.animate.set(width=7)) self.wait()
See also¶
length_over_dim()