API 参考:Mobject 基类类型(types)

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

CurvesAsSubmobjects

把多段曲线拆成独立子对象的 VMobject 容器,方便对每一段单独上色或动画。

继承关系

G Mobject Mobject VMobject VMobject Mobject->VMobject VGroup VGroup VMobject->VGroup CurvesAsSubmobjects CurvesAsSubmobjects VGroup->CurvesAsSubmobjects

参数

API 文档

class manim.CurvesAsSubmobjects(vmobject: VMobject, **kwargs)

基类:VGroup

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.ndarray

The point on the CurvesAsSubmobjects.

Raises

ValueError

If alpha is not between 0 and 1.

Exception

If the CurvesAsSubmobjects has no submobjects, or no submobject has points.

DashedVMobject

把任意 VMobject 变成虚线版:dash_length 与间距可调,常用来表示辅助线或预期位置。

继承关系

G Mobject Mobject VMobject VMobject Mobject->VMobject DashedVMobject DashedVMobject VMobject->DashedVMobject

参数

vmobject

—,VMobject

num_dashes

15,int

dashed_ratio

0.5,float

dash_offset

0,float

color

ManimColor('#FFFFFF'),ManimColor

equal_lengths

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)

基类:VMobject

ImageMobject

把本地图片文件(PNG/JPG)作为 Mobject 摆进画面,可缩放、旋转、裁剪。

继承关系

G Mobject Mobject ImageMobject ImageMobject Mobject->ImageMobject

参数

filename_or_array

—,StrPath | npt.NDArray

scale_to_resolution

1080,int

invert

False,bool

image_mode

'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)

基类:AbstractImageMobject

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

set_opacity(alpha: float) → Self

Sets the image's opacity.

Parameters

alpha

The alpha value of the object, 1 being opaque and 0 being transparent.

ImageMobjectFromCamera

捕获另一个相机画面作为图像的 Mobject,用于画中画或场景缩略预览。

继承关系

G Mobject Mobject ImageMobjectFromCamera ImageMobjectFromCamera Mobject->ImageMobjectFromCamera

参数

camera

—,MovingCamera

default_display_frame_config

None,dict[str, Any] | None

API 文档

class manim.ImageMobjectFromCamera(camera: MovingCamera, default_display_frame_config: dict[str, Any] | None = None, **kwargs: Any)

基类:AbstractImageMobject

Mobject1D

一维对象基类(v0.21 标记为内部实验类型),普通教程较少直接使用。

继承关系

G Mobject Mobject PMobject PMobject Mobject->PMobject Mobject1D Mobject1D PMobject->Mobject1D

参数

API 文档

class manim.Mobject1D(density: int = 10, **kwargs: Any)

基类:PMobject

Mobject2D

二维对象基类(内部实验类型),面片类对象的祖先。

继承关系

G Mobject Mobject PMobject PMobject Mobject->PMobject Mobject2D Mobject2D PMobject->Mobject2D

参数

API 文档

class manim.Mobject2D(density: int = 25, **kwargs: Any)

基类:PMobject

PGroup

PMobject 的专用容器:把点集对象分组统一管理。

继承关系

G Mobject Mobject PMobject PMobject Mobject->PMobject PGroup PGroup PMobject->PGroup

API 文档

class manim.PGroup(*pmobs: Any, **kwargs: Any)

基类:PMobject

PMobject

点云式 Mobject:只含离散点、无填充笔画,是 DotCloud 等实验性渲染类型的基类。

继承关系

G Mobject Mobject PMobject PMobject Mobject->PMobject

参数

API 文档

class manim.PMobject(stroke_width: int = 4, **kwargs: Any)

基类:Mobject

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 Mobject

Examples

>>> from manim import Square, RED
>>> Square(color=RED).get_color() == RED
True
static get_mobject_type_class() → type[PMobject]

Return the base class of this mobject type.

get_point_mobject(center: Point3DLike | None = None) → Point

The simplest Mobject to be transformed to or from self. Should by a point of the appropriate type

reset_points() → Self

Sets points to 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:不渲染任何可见图形,只承载位置,常作动画的锚点参数。

继承关系

G Mobject Mobject PMobject PMobject Mobject->PMobject Point Point PMobject->Point

参数

location

array([0., 0., 0.]),Point3DLike

color

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)

基类:PMobject

generate_points() → Self

Initializes points and therefore the shape.

Gets called upon creation. This is an empty method that can be implemented by subclasses.

PointCloudDot

把点集渲染成一群小圆点的 PMobject 显示形式,适合散点可视化。

继承关系

G Mobject Mobject PMobject PMobject Mobject->PMobject Mobject1D Mobject1D PMobject->Mobject1D PointCloudDot PointCloudDot Mobject1D->PointCloudDot

参数

center

array([0., 0., 0.]),Point3DLike

radius

2.0,float

stroke_width

2,int

density

10,int

color

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)

基类:Mobject1D

generate_points() → Self

Initializes points and therefore the shape.

Gets called upon creation. This is an empty method that can be implemented by subclasses.

VDict

「键值对版 VGroup」:按键名索引子对象,方便在公式字典里做局部替换。

继承关系

G Mobject Mobject VMobject VMobject Mobject->VMobject VDict VDict VMobject->VDict

参数

mapping_or_iterable

{}

show_keys

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)

基类:VMobject

add(mapping_or_iterable: Mapping[Hashable, VMobject] | Iterable[tuple[Hashable, VMobject]]) → Self

Adds the key-value pairs to the VDict object.

Also, it internally adds the value to the submobjects list of Mobject, which is responsible for actual on-screen display.

Parameters

mapping_or_iterable

The parameter specifying the key-value mapping of keys and mobjects.

Returns

VDict

Returns the VDict object on which this method was called.

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 to submob_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 VDict object

Returns

dict_values

All the submobjects associated with the VDict object

Examples

Normal usage:

for submob in my_dict.get_all_submobjects():
    self.play(Create(submob))
remove(key: Hashable) → Self

Removes the mobject from the VDict object having the key key

Also, it internally removes the mobject from the submobjects list of Mobject, (which is responsible for removing it from the screen)

Parameters

key

The key of the submoject to be removed.

Returns

VDict

Returns the VDict object on which this method was called.

Examples

Normal usage:

my_dict.remove("square")

VGroup

VMobject 专用容器:子对象都是 VMobject,可使用只有矢量对象才有的整体方法(如 set_stroke),是日常最常用组合器。

继承关系

G Mobject Mobject VMobject VMobject Mobject->VMobject VGroup VGroup VMobject->VGroup

快速上手

vg = VGroup(circle, square, dot)
vg.arrange(RIGHT)

API 文档

class manim.VGroup(*vmobjects: VMobject | Iterable[VMobject], **kwargs: Any)

基类:VMobject

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

VGroup

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、贝塞尔操作都从这里来。

继承关系

G Mobject Mobject VMobject VMobject Mobject->VMobject

参数

fill_color

None

fill_opacity

0.0,float

stroke_color

None

stroke_opacity

1.0,float

stroke_width

4,float

background_stroke_color

ManimColor('#000000')

background_stroke_opacity

1.0,float

background_stroke_width

0,float

sheen_factor

0.0,float

joint_type

None,LineJointType | None

sheen_direction

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

close_new_points

False,bool

pre_function_handle_to_anchor_scale_factor

0.01,float

make_smooth_after_applying_functions

False,bool

background_image

None,Image | str | None

shade_in_3d

False,bool

tolerance_for_point_equality

1e-06,float

n_points_per_cubic_curve

4,int

cap_style

<CapStyleType.AUTO: 0>,CapStyleType

快速上手

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)

基类:Mobject

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

VMobject

self

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

VMobject

self

add_points_as_corners(points: Point3DLike_Array) → Self

Append multiple straight lines at the end of VMobject.points, which connect the given points in order starting from the end of the current path. These points would 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

VMobject

The 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

VMobject

self

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

VMobject

self

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

VMobject

self

See also

interpolate(), align_data()

append_points(new_points: Point3DLike_Array) → Self

Append the given new_points to the end of VMobject.points.

Parameters

new_points

An array of 3D points to append.

Returns

VMobject

The 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

VMobject

self

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 ---------- p0

first 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 Mobject

Examples

>>> 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

**kwargs

The 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 Circle is counterclockwise:

>>> from manim import Circle
>>> Circle().get_direction()
'CCW'

Returns

str

Either "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

static get_mobject_type_class() → type[VMobject]

Return the base class of this mobject type.

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.

lengthfloat

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

lengthfloat

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 Mobject to 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() (or consider_points_equals_2d() when n_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 x and y coordinates. 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

VMobject

self

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.ndarray

The point on the VMobject.

Raises

ValueError

If alpha is not between 0 and 1.

Exception

If the VMobject has 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 VMobject vmobject, a lower bound a and an upper bound b, modify this VMobject's points to match the portion of the Bézier spline described by vmobject.points with the parameter t between a and b.

Parameters

vmobject

The VMobject that will serve as a model.

a

The lower bound for t.

b

The upper bound for t

Returns

VMobject

The VMobject itself, after the transformation.

Raises

TypeError

If vmobject is not an instance of VMobject.

proportion_from_point(point: Point3DLike) → float

Returns the proportion along the path of the VMobject a 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

ValueError

If point does not lie on the curve.

Exception

If the VMobject has 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 resize function.

reverse_direction() → Self

Reverts the point direction by inverting the point order.

Returns

VMobject

Returns 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 Mobject around a specified axis and point.

Parameters

angle

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

axis

The rotation axis (see Rotating for 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

Mobject

self (for method chaining)

备注

To animate a rotation, use Rotating or Rotate instead 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

set_sheen_direction()

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

VMobject

self

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

VMobject

self

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

VMobject

self

set_cap_style(cap_style: CapStyleType) → Self

Sets the cap style of the VMobject.

Parameters

cap_style

The cap style to be set. See CapStyleType for options.

Returns

VMobject

self

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

color

Fill color of the VMobject.

opacity

Fill opacity of the VMobject.

family

If True, the fill color of all submobjects is also set.

Returns

VMobject

self

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

VMobject

The 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

set_sheen() rotate_sheen_direction()

start_new_path(point: Point3DLike) → Self

Append a point to the VMobject.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 of VMobject.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

VMobject

The VMobject itself, after appending point and starting a new curve.

VectorizedPoint

带矢量渲染能力的点对象(Point 的 VMobject 版本),内部实验用途居多。

继承关系

G Mobject Mobject VMobject VMobject Mobject->VMobject VectorizedPoint VectorizedPoint VMobject->VectorizedPoint

参数

location

array([0., 0., 0.]),Point3DLike

color

ManimColor('#000000'),ManimColor

fill_opacity

0,float

stroke_width

0,float

artificial_width

0.01,float

artificial_height

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

basecls

VMobject 的别名

property height: float

The height of the mobject.

Returns

float

Examples

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

float

Examples

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()