handanim.primitives Package¶
handanim.primitives.lines¶
- class handanim.primitives.lines.Line(start, end, *args, **kwargs)[source]¶
Bases:
DrawableA drawable line primitive that generates hand-drawn style lines with randomized jitter and bowing effects.
Supports customizable stroke and sketch styles, with options for line curvature, roughness, and multiple line passes to create a hand-drawn appearance. Allows for optional stroke pressure variations and provides methods to draw single or overlapping lines.
- start¶
Starting point coordinates of the line
- Type:
np.ndarray
- end¶
Ending point coordinates of the line
- Type:
np.ndarray
- class handanim.primitives.lines.LinearPath(points, close=False, *args, **kwargs)[source]¶
Bases:
DrawableA drawable linear path that connects a series of points, with optional closing of the path.
- close¶
Whether to connect the last point back to the first point. Defaults to False.
- Type:
bool, optional
- Raises:
ValueError – If fewer than two points are provided.
- Parameters:
The path is drawn by creating Line objects between consecutive points, with optional path closure if specified.
handanim.primitives.arrow¶
- class handanim.primitives.arrow.Arrow(start_point, end_point, arrow_head_type='->', arrow_head_size=10.0, arrow_head_angle=45.0, *args, **kwargs)[source]¶
Bases:
Drawable- Parameters:
handanim.primitives.polygons¶
- class handanim.primitives.polygons.Polygon(points, *args, **kwargs)[source]¶
Bases:
DrawableA Polygon class representing a drawable polygon shape.
This class allows creating polygons with a list of points, drawing them with optional stroke and fill styles. It ensures the polygon has at least three points and can render the polygon using a closed linear path with optional filling.
- Raises:
ValueError – If fewer than three points are provided.
- Parameters:
- class handanim.primitives.polygons.Rectangle(top_left, width, height, *args, **kwargs)[source]¶
Bases:
PolygonA Rectangle class representing a rectangular polygon shape.
This class creates a rectangle by specifying its top-left corner coordinates, width, and height. It inherits from the Polygon class and generates the four vertices of the rectangle automatically.
- Parameters:
- class handanim.primitives.polygons.Square(top_left, side_length, *args, **kwargs)[source]¶
Bases:
Rectangle
handanim.primitives.ellipse¶
- class handanim.primitives.ellipse.Ellipse(center, width, height, *args, **kwargs)[source]¶
Bases:
DrawableA drawable ellipse primitive with sketchy rendering capabilities.
Supports customizable center, width, height, and sketch-style rendering with optional multi-stroke and roughness effects. Allows for generating ellipses with randomized point generation and stroke variations.
- center¶
The center point of the ellipse
- Type:
np.ndarray
- class handanim.primitives.ellipse.Circle(center, radius, *args, **kwargs)[source]¶
Bases:
EllipseA specialized Ellipse where the x and y radii are equal, creating a perfect circle.
- class handanim.primitives.ellipse.GlowDot(center, radius=1, *args, **kwargs)[source]¶
Bases:
DrawableA drawable glowing dot with customizable center, radius, and opacity scaling.
Renders a dot with multiple overlapping layers of decreasing opacity and increasing radius to create a glowing effect.
- Parameters:
handanim.primitives.curves¶
- class handanim.primitives.curves.Curve(points, *args, **kwargs)[source]¶
Bases:
DrawableA class representing a curve that can be drawn with a sketchy, hand-drawn style.
Allows creating curves with multiple points, supporting various drawing techniques including single line, quadratic, and more complex multi-point curves with randomization to simulate hand-drawn appearance.
- points¶
List of points defining the curve’s shape.
- Type:
List[np.ndarray]
- draw_single_curve(opsset, points=None, close_point=None)[source]¶
Draws a single human style sketchy curve
handanim.primitives.text¶
- class handanim.primitives.text.CustomPen(glyphSet, scale=0.01)[source]¶
Bases:
BasePen- Parameters:
scale (float)
- class handanim.primitives.text.Text(text, position=(0.0, 0.0), font_size=12, *args, **kwargs)[source]¶
Bases:
DrawableA Drawable text primitive that renders text using single-line or outline font glyphs.
Supports TTF fonts (type=”ttf”), open-path SVG 1.1 single-line plotter fonts (type=”svg”, e.g. “casual_hand”, “blueprint_sans”, “architect_hand”), custom skeletonized JSON fonts (type=”custom”), and Hershey stroke fonts (type=”hershey”), plus built-in open-stroke fallbacks for symbols like ₹.
- wrap(bbox, line_height_factor=1.5)[source]¶
Pre-compute line breaks so that no line of text exceeds bbox.width.
- Parameters:
bbox (BoundingBox)
line_height_factor (float)
- autofit(bbox)[source]¶
- Parameters:
bbox (BoundingBox)
handanim.primitives.math¶
- class handanim.primitives.math.Math(tex_expression, position, font_size=12, font_name='feasibly', *args, **kwargs)[source]¶
Bases:
DrawableA Drawable class for rendering mathematical expressions using TeX notation.
Parses a TeX expression via matplotlib’s MathTextParser and renders individual glyphs using the specified font backend.
- tex_expression¶
The TeX expression to render.
- position¶
Top-left anchor (x, y) for the rendered expression.
- font_size¶
Logical font size; the base unit is 10 (scale_factor = font_size / 10).
- font_name¶
Font backend to use (see stylings/fonts.py).
handanim.primitives.captions¶
- class handanim.primitives.captions.CaptionWord(word, start, end, speaker=None, em=False, color=None)[source]¶
Bases:
objectNormalized word timing entry for Captions.
- Parameters:
- class handanim.primitives.captions.CaptionsAnimation(captions=None, start_time=0.0, duration=None, easing_fun=None, data=None)[source]¶
Bases:
AnimationEventSingle timeline event that drives a Captions drawable across the narration duration.
- class handanim.primitives.captions.Captions(clip, words_per_chunk=3, highlight=(1.0, 0.0, 0.0), color=(0.0, 0.0, 0.0), y=1590.0, x=None, font_size=48, font_name=None, align='center', word_spacing=None, max_width=960.0, start_time=0.0, max_hold_gap=0.25, stroke_style=None, sketch_style=None, highlight_stroke_width=None, speaker_colors=None, speaker_highlights=None, secondary_highlight=None, highlight_numbers=False, background_color=None, background_opacity=0.85, background_padding=14.0, **kwargs)[source]¶
Bases:
DrawableWord-timed narration captions rendered as a single drawable + single animation event.
Groups spoken words from clip into chunks of words_per_chunk, pre-caches base and highlighted OpsSet`s for each word, and highlights the active word at any timestamp `t.
Usage:
captions = Captions(clip, words_per_chunk=3, highlight=RED, y=1590) scene.overlay.add(captions)
- Parameters:
clip (Any)
words_per_chunk (int)
y (float)
x (float | None)
font_size (int)
font_name (str | None)
align (str)
word_spacing (float | None)
max_width (float | None)
start_time (float)
max_hold_gap (float)
stroke_style (StrokeStyle | None)
sketch_style (SketchStyle | None)
highlight_stroke_width (float | None)
highlight_numbers (bool)
background_opacity (float)
background_padding (float)
- set_default_x(center_x)[source]¶
Set default horizontal anchor if x was not explicitly provided.
- Parameters:
center_x (float)
- Return type:
None
- get_active_chunk_index(t)[source]¶
Return the index of the caption chunk active at timestamp t, or None.
- draw_at_time(t)[source]¶
Return the OpsSet for the caption chunk active at timestamp t (in seconds).
handanim.primitives.character¶
- handanim.primitives.character.solve_two_joint_ik(root_pos, mid_pos, end_pos, target_pos, bend_direction=1)[source]¶
Solve 2D two-bone analytic inverse kinematics using the Law of Cosines.
Given rest joint positions (root_pos, mid_pos, end_pos) and a desired target_pos (in the same coordinate frame as root_pos), returns the local rotation angles (upper_angle_deg, lower_angle_deg) for a parent-child bone pair so that end_pos reaches target_pos (or stretches toward it if out of reach).
- Parameters:
root_pos (tuple[float, float]) – Rest position of the root joint (e.g. shoulder or hip).
mid_pos (tuple[float, float]) – Rest position of the middle joint (e.g. elbow or knee).
end_pos (tuple[float, float]) – Rest position of the end effector (e.g. wrist/hand or ankle/foot).
target_pos (tuple[float, float]) – Desired position for the end effector.
bend_direction (int) – +1 or -1 selecting which side the middle joint bends toward.
- Returns:
Tuple (upper_angle_deg, lower_angle_deg) in degrees.
- Return type:
- class handanim.primitives.character.Pose(angles=<factory>, offsets=<factory>, scales=<factory>, ik_targets=<factory>, variants=<factory>)[source]¶
Bases:
objectDeclarative snapshot of a CharacterRig configuration.
- Parameters:
- offsets¶
Mapping of node name to local (dx, dy) translation offset.
- scales¶
Mapping of node name to local (sx, sy) scale multiplier.
- ik_targets¶
Mapping of limb name to world-space (x, y) target point.
- class handanim.primitives.character.RigNode(name, pivot=(0.0, 0.0), drawables=None, children=None, angle=0.0, offset=(0.0, 0.0), scale_factor=(1.0, 1.0), *args, **kwargs)[source]¶
Bases:
DrawableA hierarchical transform node with its own pivot and child nodes.
Children attached to a RigNode inherit its rotation (around pivot), scale (around pivot), and translation (offset).
- Parameters:
- add_child(child_or_name, pivot=None, drawables=None, children=None, angle=0.0, offset=(0.0, 0.0), scale_factor=(1.0, 1.0), *args, **kwargs)[source]¶
- has_scheduled_variants()[source]¶
Return True if this node or any descendant VariantSlot has a non-empty time schedule.
- Return type:
- class handanim.primitives.character.VariantSlot(name, variants=None, default=None, pivot=(0.0, 0.0), *args, **kwargs)[source]¶
Bases:
RigNodeA swappable sprite/shape slot (e.g. eyes or mouth) attached to a parent RigNode.
Inherits all parent transforms while switching its active drawable based on the current Pose.variants[name] or a scheduled time series.
- Parameters:
- add_periodic_switch(start_time, end_time, pulse_variant='blink', base_variant=None, period=3.2, pulse_duration=0.11)[source]¶
Schedule periodic brief switches (e.g. eye blinks) between start_time and end_time.
- class handanim.primitives.character.TwoJointLimb(name, upper_node, lower_node, effector_pos, bend_direction=1)[source]¶
Bases:
objectTwo-bone inverse kinematics chain descriptor (e.g. upper arm + forearm).
- Parameters:
- lower_node¶
Name of the lower RigNode (e.g. “forearm_r”), which must be a child of upper_node.
- Type:
- effector_pos¶
Rest position of the end effector (e.g. hand/wrist or foot).
- class handanim.primitives.character.CharacterRig(root=None, limbs=None, rest_pose=None, pivot=(0.0, 0.0), *args, **kwargs)[source]¶
Bases:
DrawableArticulated 2D character rig combining hierarchical
RigNodeobjects,TwoJointLimbIK, andVariantSlotnodes.- Parameters:
- limbs: dict[str, TwoJointLimb]¶
- add_child(child_or_name, pivot=None, drawables=None, children=None, angle=0.0, offset=(0.0, 0.0), scale_factor=(1.0, 1.0), *args, **kwargs)[source]¶
Attach a child RigNode directly to self.root.
- add_slot(slot_or_name, variants=None, default=None, pivot=None, *args, **kwargs)[source]¶
Attach a VariantSlot directly to self.root.
- add_limb(limb)[source]¶
- Parameters:
limb (TwoJointLimb)
- Return type:
None
- add_two_joint_limb(name, parent=None, root_pivot=(0.0, 0.0), length1=80.0, length2=70.0, bend_direction=1, *, mid_pivot=None, effector_pos=None, effector=None, upper_node=None, lower_node=None, upper_drawables=None, lower_drawables=None, stroke_style=None, sketch_style=None)[source]¶
Create or register a two-joint IK limb (upper_node -> lower_node) on this rig.
- has_scheduled_variants()[source]¶
Return True if any VariantSlot in this rig has a non-empty time schedule.
- Return type:
- transform_point_for_node(node_name, point, pose=None)[source]¶
Transform a rest-space point attached to node_name into world coordinates under pose.
- get_joint_world_pos(node_name, pose=None)[source]¶
Return the world-space position of node_name’s pivot under pose.
- get_limb_effector_world_pos(limb_name, pose=None)[source]¶
Return the world-space position of a TwoJointLimb’s end effector under pose.
- resolve_pose(pose=None)[source]¶
Merge pose with rest_pose and solve any ik_targets into concrete joint angles.
- reach(limb_name, target_pos, base_pose=None)[source]¶
Return a new Pose with limb_name’s IK angles solved to reach target_pos.
- point_at(scene, target, limb_name=None, start_time=0.0, duration=0.5, hold=1.0, return_duration=0.45, return_to_rest=True, base_pose=None, overlay=False)[source]¶
Animate limb_name reaching/pointing toward target (a Drawable or (x, y) tuple).
Returns the created PoseAnimation (and registers it on scene if scene is provided).
- sync_to_audio(scene, audio_clip, start_time=0.0, mouth_slot='mouth', open_variant='open', closed_variant='neutral', smile_variant='smile', head_node='head', head_bob_angle=2.0, interval=0.11, overlay=False)[source]¶
Drive mouth VariantSlot lip-sync and subtle head bobbing from audio_clip.
Reads word timing intervals (and WAV amplitude envelope when available) from audio_clip to schedule mouth switches on mouth_slot, and creates a PoseAnimation spanning the narration duration so draw_with_pose(…, time=t) is evaluated on every frame.
handanim.primitives.flowchart¶
- class handanim.primitives.flowchart.FlowchartNode(label, position, size=(100.0, 50.0), font_size=12, stroke_style=<handanim.core.styles.StrokeStyle object>, sketch_style=<handanim.core.styles.SketchStyle object>, fill_style=None, **kwargs)[source]¶
Bases:
DrawableGroupA flowchart process node: a Rectangle with a centered Text label.
position is the center of the node in world coordinates.
- Parameters:
- class handanim.primitives.flowchart.FlowchartDiamond(label, position, size=(100.0, 60.0), font_size=12, stroke_style=<handanim.core.styles.StrokeStyle object>, sketch_style=<handanim.core.styles.SketchStyle object>, fill_style=None, **kwargs)[source]¶
Bases:
DrawableGroupA flowchart decision node: a diamond polygon with a centered Text label.
position is the center. size = (width, height) of the diamond’s bounding box.
- Parameters:
- class handanim.primitives.flowchart.FlowchartConnector(from_node, to_node, from_side='bottom', to_side='top', label=None, label_font_size=10, arrow_head_type='->', arrow_head_size=10.0, arrow_head_angle=45.0, *args, **kwargs)[source]¶
Bases:
DrawableAn auto-routed arrow between two flowchart nodes.
Computes an elbow route from from_node.get_anchor(from_side) to to_node.get_anchor(to_side) at draw time so that moving a node automatically updates the connector without re-construction.
For straight lines (same axis, opposing sides, perfectly aligned), a single Arrow is drawn. Otherwise an L-shaped elbow is used: the connector exits from_node in the from_side direction, turns once at the midpoint, then arrives at to_node from the to_side direction.
- Parameters:
from_node (FlowchartNode | FlowchartDiamond)
to_node (FlowchartNode | FlowchartDiamond)
from_side (str)
to_side (str)
label (str | None)
label_font_size (int)
arrow_head_type (str)
arrow_head_size (float)
arrow_head_angle (float)
- class handanim.primitives.flowchart.Flowchart(nodes, connectors, **kwargs)[source]¶
Bases:
DrawableGroupA complete flowchart assembled from FlowchartNode, FlowchartDiamond, and FlowchartConnector primitives.
Prefer constructing via Flowchart.from_dict(spec) rather than directly.
- Parameters:
nodes (list[DrawableGroup])
connectors (list[FlowchartConnector])
- classmethod from_dict(spec, **kwargs)[source]¶
Build a Flowchart from a declarative spec dict.
Expected format:
{ "nodes": [ { "id": "start", "type": "node", # "node" (default) or "diamond" "label": "Start", "position": [100, 50], "size": [100, 40], # optional "font_size": 12, # optional }, ... ], "edges": [ { "from": "start", "to": "decision", "from_side": "bottom", # optional, default "bottom" "to_side": "top", # optional, default "top" "label": "Yes", # optional edge label }, ... ], }
Additional keys in each node or edge dict are forwarded as keyword arguments to the underlying primitive (e.g. stroke_style, fill_style).
handanim.primitives.table¶
- class handanim.primitives.table.TableRevealEvent(pairs)[source]¶
Bases:
CompositeAnimationEventA CompositeAnimationEvent that pairs each sub-event with its target drawable.
Returned by Table.animate_by_row() and Table.animate_by_cell(). Because Scene.add() always requires an explicit drawable, callers must unpack these pairs themselves — use add_to_scene() as a one-liner convenience.
- Parameters:
pairs (list[tuple[Any, DrawableGroup]])
- pairs¶
List of (AnimationEvent, DrawableGroup) in reveal order.
Usage:
reveal = table.animate_by_row(SketchAnimation, start_time=0, total_duration=3) reveal.add_to_scene(scene) # or inspect and filter manually: for event, drawable in reveal.pairs: scene.add(event, drawable)
- class handanim.primitives.table.Table(top_left, n_rows, n_cols, cell_width, cell_height, data=None, headers=None, cell_font_size=12, header_font_size=14, font_name=None, text_align='left', stroke_style=<handanim.core.styles.StrokeStyle object>, sketch_style=<handanim.core.styles.SketchStyle object>, fill_style=None, header_fill_style=None, header_stroke_style=None, **kwargs)[source]¶
Bases:
DrawableGroupA grid of Rectangle + Text cells with optional header-row styling.
Each cell is a DrawableGroup([rect, text]) stored in self.cells[row][col]. Row groups (self.row_groups[r]) contain the leaf rect/text drawables for all cells in that row — they are kept flat (no nested DrawableGroups) so that group-level scene animations apply correctly.
The Table itself is a flat parallel DrawableGroup of all leaf drawables, so scene.add(event, table) animates every cell simultaneously.
- Parameters:
top_left (tuple[float, float]) – (x, y) world coordinates of the table’s top-left corner.
n_rows (int) – Total rows, including the header row if headers is provided.
n_cols (int) – Number of columns.
cell_width (float) – Width of each cell in world units.
cell_height (float) – Height of each cell in world units.
data (list[list[str]] | None) – 2-D list of cell strings, indexed [row][col]. Rows with a header start at data[0] = row 1 of the grid. Missing entries default to “”.
headers (list[str] | None) – Column header strings for row 0. If provided, row 0 uses header_stroke_style / header_fill_style instead of the defaults.
cell_font_size (int) – Font size for data cells.
header_font_size (int) – Font size for header cells.
stroke_style (StrokeStyle) – Stroke style for data cells.
sketch_style (SketchStyle) – Sketch style shared by all cells.
fill_style (FillStyle | None) – Fill style for data cells (None = no fill).
header_stroke_style (StrokeStyle | None) – Override stroke style for header cells.
header_fill_style (FillStyle | None) – Override fill style for header cells.
font_name (str | None)
text_align (str)
- animate_by_row(anim_class, start_time=0.0, total_duration=1.0, **anim_kwargs)[source]¶
Build a staggered row-reveal animation.
Each row gets an equal slice of total_duration, starting after the previous row’s slice begins. All cells in a row animate in parallel.
- Parameters:
- Returns:
TableRevealEvent whose .add_to_scene(scene) registers all pairs.
- Return type:
- animate_by_cell(anim_class, start_time=0.0, total_duration=1.0, **anim_kwargs)[source]¶
Build a staggered cell-reveal animation in row-major order.
Each cell gets an equal slice of total_duration. Both the rect and the text inside a cell animate together (the cell’s DrawableGroup is the target).
- Parameters:
- Returns:
TableRevealEvent whose .add_to_scene(scene) registers all pairs.
- Return type:
handanim.primitives.vector_svg¶
Vector SVG - authored by Hamd Waseem (https://github.com/hamdivazim/)
A drawable class that accepts an SVG document and renders it as a Drawable as close to the original SVG as possible.
- class handanim.primitives.vector_svg.VectorSVG(svg_doc, position=(0, 0), *args, **kwargs)[source]¶
Bases:
DrawableA drawable class that accepts an SVG document and renders it as a Drawable as close to the original SVG as possible.
Note
This feature was contributed by Hamd Waseem (https://github.com/hamdivazim).
- svg_doc¶
The parsed SVG document object from svgelements.
- classmethod from_svg_file(svg_file_path, *args, **kwargs)[source]¶
Create a VectorSVG instance from a file path
handanim.primitives.raster_image¶
- class handanim.primitives.raster_image.RasterImage(image_path, position=(0, 0), width=None, height=None, opacity=1.0, **kwargs)[source]¶
Bases:
DrawableA drawable that places a raster image (PNG, JPEG, etc.) into the scene.
The image is positioned in world coordinates. If only one of width/height is given, the other is computed to preserve the aspect ratio. If neither is given, the image’s pixel dimensions are used as world-coordinate size.
- Parameters:
image_path (str) – Path to the image file.
position (tuple[float, float]) – Top-left corner in world coordinates (x, y).
width (float | None) – Display width in world coordinates.
height (float | None) – Display height in world coordinates.
opacity (float) – Initial opacity (0.0 transparent, 1.0 opaque).
handanim.primitives.eraser¶
- class handanim.primitives.eraser.Eraser(objects_to_erase, drawable_cache=None, *args, **kwargs)[source]¶
Bases:
DrawableA Drawable representing an eraser that can remove specified drawable objects.
- Parameters:
drawable_cache (DrawableCache | None)
- drawable_cache¶
Cache used for calculating bounding box of objects to erase.
- Type:
The draw method generates a zigzag motion over the bounding box of the objects to be erased, using an expanded pen width to create a pastel blend erasing effect.