handanim.primitives Package

handanim.primitives.lines

class handanim.primitives.lines.Line(start, end, *args, **kwargs)[source]

Bases: Drawable

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

Parameters:
start

Starting point coordinates of the line

Type:

np.ndarray

end

Ending point coordinates of the line

Type:

np.ndarray

draw_single_line(opsset, move=False, overlay=False)[source]
Parameters:
Return type:

OpsSet

draw()[source]

Draws a hand-drawn-like line with some jitter.

Return type:

OpsSet

class handanim.primitives.lines.LinearPath(points, close=False, *args, **kwargs)[source]

Bases: Drawable

A drawable linear path that connects a series of points, with optional closing of the path.

points

A list of (x, y) coordinate points defining the path.

Type:

List[tuple[float, float]]

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.

draw()[source]

Provides the list of operations to be performed to draw this particular drawable object on the canvas

Return type:

OpsSet

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:
draw()[source]

Provides the list of operations to be performed to draw this particular drawable object on the canvas

class handanim.primitives.arrow.CurvedArrow(points, arrow_head_type='->', arrow_head_size=10.0, arrow_head_angle=45.0, *args, **kwargs)[source]

Bases: Drawable

Parameters:
draw()[source]

Provides the list of operations to be performed to draw this particular drawable object on the canvas

Return type:

OpsSet

handanim.primitives.polygons

class handanim.primitives.polygons.Polygon(points, *args, **kwargs)[source]

Bases: Drawable

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

points

A list of (x, y) coordinates defining the polygon vertices.

Type:

List[tuple[float, float]]

Raises:

ValueError – If fewer than three points are provided.

Parameters:

points (list[tuple[float, float]])

draw()[source]

Draw a polygon with the given points

Return type:

OpsSet

class handanim.primitives.polygons.Rectangle(top_left, width, height, *args, **kwargs)[source]

Bases: Polygon

A 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:
  • top_left (tuple[float, float]) – Coordinates of the top-left corner of the rectangle.

  • width (float) – Width of the rectangle.

  • height (float) – Height of the rectangle.

get_bbox()[source]
Return type:

BoundingBox

class handanim.primitives.polygons.NGon(center, radius, n, *args, **kwargs)[source]

Bases: Polygon

Parameters:
class handanim.primitives.polygons.Square(top_left, side_length, *args, **kwargs)[source]

Bases: Rectangle

Parameters:
class handanim.primitives.polygons.RoundedRectangle(top_left, width, height, border_radius=0.1, *args, **kwargs)[source]

Bases: Drawable

Parameters:
get_bbox()[source]
Return type:

BoundingBox

draw()[source]

Provides the list of operations to be performed to draw this particular drawable object on the canvas

Return type:

OpsSet

class handanim.primitives.polygons.RoundedSquare(top_left, side_length, border_radius=0.1, *args, **kwargs)[source]

Bases: RoundedRectangle

Parameters:

handanim.primitives.ellipse

class handanim.primitives.ellipse.Ellipse(center, width, height, *args, **kwargs)[source]

Bases: Drawable

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

Parameters:
center

The center point of the ellipse

Type:

np.ndarray

width

The width of the ellipse

Type:

float

height

The height of the ellipse

Type:

float

draw_ellipse_border(opsset)[source]
Parameters:

opsset (OpsSet)

Return type:

tuple[list, OpsSet]

draw()[source]

Draw a sketchy version of an ellipse

Return type:

OpsSet

class handanim.primitives.ellipse.Circle(center, radius, *args, **kwargs)[source]

Bases: Ellipse

A specialized Ellipse where the x and y radii are equal, creating a perfect circle.

Parameters:
  • center (tuple[float, float]) – The center coordinates of the circle.

  • radius (float) – The radius of the circle.

class handanim.primitives.ellipse.GlowDot(center, radius=1, *args, **kwargs)[source]

Bases: Drawable

A 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:
  • center (Tuple[float, float]) – The center coordinates of the dot.

  • radius (float, optional) – The base radius of the dot. Defaults to 1.

draw()[source]

Draw a perfect glowing dot

Return type:

OpsSet

handanim.primitives.curves

class handanim.primitives.curves.Curve(points, *args, **kwargs)[source]

Bases: Drawable

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

Parameters:

points (list[tuple[float, float]])

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

Parameters:
Return type:

OpsSet

draw_single_curve_with_randomization(opsset, points=None, offset=1.0)[source]

Draw a single human style sketchy curve with random derivations

Parameters:
Return type:

OpsSet

draw()[source]

Draw the curve

Return type:

OpsSet

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

A 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 ₹.

Parameters:
get_random_font_choice()[source]

Return (font_choice, font_path_or_id) for the resolved font.

Return type:

tuple[str, str]

get_glyph_strokes(char)[source]

Return (glyph_opsset, advance_width) for char in world units.

Parameters:

char (str)

Return type:

tuple[OpsSet, float]

get_glyph_space()[source]

Return (space_width, glyph_scale) in world units.

Return type:

tuple[float, float]

wrap(bbox, line_height_factor=1.5)[source]

Pre-compute line breaks so that no line of text exceeds bbox.width.

Parameters:
autofit(bbox)[source]
Parameters:

bbox (BoundingBox)

draw()[source]

Provides the list of operations to be performed to draw this particular drawable object on the canvas

Return type:

OpsSet

handanim.primitives.math

class handanim.primitives.math.Math(tex_expression, position, font_size=12, font_name='feasibly', *args, **kwargs)[source]

Bases: Drawable

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

Parameters:
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).

load_font()[source]
Return type:

None

standard_glyph_opsset(unicode, font_size)[source]
Parameters:
  • unicode (int)

  • font_size (int)

Return type:

tuple[OpsSet, float, float]

custom_glyph_opsset(unicode, font_size)[source]
Parameters:
  • unicode (int)

  • font_size (int)

Return type:

tuple[OpsSet, float, float]

hershey_glyph_opsset(unicode, font_size)[source]
Parameters:
  • unicode (int)

  • font_size (int)

Return type:

tuple[OpsSet, float, float]

get_glyph_opsset(unicode, font_size)[source]
Parameters:
  • unicode (int)

  • font_size (int)

Return type:

tuple[OpsSet, float, float]

draw()[source]

Provides the list of operations to be performed to draw this particular drawable object on the canvas

Return type:

OpsSet

handanim.primitives.captions

class handanim.primitives.captions.CaptionWord(word, start, end, speaker=None, em=False, color=None)[source]

Bases: object

Normalized word timing entry for Captions.

Parameters:
word: str
start: float
end: float
speaker: str | None = None
em: bool = False
color: tuple[float, float, float] | None = None
class handanim.primitives.captions.CaptionsAnimation(captions=None, start_time=0.0, duration=None, easing_fun=None, data=None)[source]

Bases: AnimationEvent

Single timeline event that drives a Captions drawable across the narration duration.

Parameters:
apply(opsset, raw_progress)[source]

Public entry point called by Scene. Applies easing (if any) then delegates to _apply(). Do not override in subclasses — implement _apply() instead.

Parameters:
Return type:

OpsSet

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

Word-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:
x: float | None
max_width: float | None
speaker_colors: dict[str, tuple[float, float, float]]
speaker_highlights: dict[str, tuple[float, float, float]]
property chunks: list[_BuiltCaptionChunk]
property duration: 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.

Parameters:

t (float)

Return type:

int | None

draw_at_time(t)[source]

Return the OpsSet for the caption chunk active at timestamp t (in seconds).

Parameters:

t (float)

Return type:

OpsSet

to_event()[source]

Create the CaptionsAnimation event that drives this Captions drawable.

Return type:

CaptionsAnimation

draw()[source]

Draw the first chunk in its initial state (used for static bbox / cache initialization).

Return type:

OpsSet

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:

tuple[float, float]

class handanim.primitives.character.Pose(angles=<factory>, offsets=<factory>, scales=<factory>, ik_targets=<factory>, variants=<factory>)[source]

Bases: object

Declarative snapshot of a CharacterRig configuration.

Parameters:
angles

Mapping of node name to local rotation delta in degrees.

Type:

dict[str, float]

offsets

Mapping of node name to local (dx, dy) translation offset.

Type:

dict[str, tuple[float, float]]

scales

Mapping of node name to local (sx, sy) scale multiplier.

Type:

dict[str, tuple[float, float]]

ik_targets

Mapping of limb name to world-space (x, y) target point.

Type:

dict[str, tuple[float, float]]

variants

Mapping of VariantSlot name to active variant key.

Type:

dict[str, str]

angles: dict[str, float]
offsets: dict[str, tuple[float, float]]
scales: dict[str, tuple[float, float]]
ik_targets: dict[str, tuple[float, float]]
variants: dict[str, str]
copy()[source]
Return type:

Pose

get_angle(name)[source]
Parameters:

name (str)

Return type:

float

get_offset(name)[source]
Parameters:

name (str)

Return type:

tuple[float, float]

get_scale(name)[source]
Parameters:

name (str)

Return type:

tuple[float, float]

get_variant(name, default)[source]
Parameters:
Return type:

str

interpolate(other, progress)[source]

Linearly interpolate joint angles, offsets, scales, and IK targets.

Parameters:
Return type:

Pose

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

A 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:
drawables: list[Drawable]
children: list[RigNode]
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]
Parameters:
Return type:

RigNode

add_slot(slot_or_name, variants=None, default=None, pivot=None, *args, **kwargs)[source]
Parameters:
Return type:

VariantSlot

has_scheduled_variants()[source]

Return True if this node or any descendant VariantSlot has a non-empty time schedule.

Return type:

bool

find_node(name)[source]
Parameters:

name (str)

Return type:

RigNode | None

find_path(name)[source]
Parameters:

name (str)

Return type:

list[RigNode] | None

get_local_transform_params(pose=None)[source]
Parameters:

pose (Pose | None)

Return type:

tuple[float, tuple[float, float], tuple[float, float]]

draw_with_pose(pose=None, time=None)[source]

Evaluate this node and all descendants under pose via forward kinematics.

Parameters:
Return type:

OpsSet

draw(time=None)[source]

Provides the list of operations to be performed to draw this particular drawable object on the canvas

Parameters:

time (float | None)

Return type:

OpsSet

class handanim.primitives.character.VariantSlot(name, variants=None, default=None, pivot=(0.0, 0.0), *args, **kwargs)[source]

Bases: RigNode

A 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:
schedule: list[tuple[float, str]]
set_schedule(entries)[source]

Set a time-sorted schedule of (timestamp, variant_name) switches.

Parameters:

entries (Sequence[tuple[float, str]])

Return type:

None

add_switch(time, variant_name)[source]

Schedule a switch to variant_name at time (in seconds).

Parameters:
Return type:

None

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.

Parameters:
Return type:

None

add_cycle(start_time, end_time, variants=None, interval=0.14, rest_variant=None)[source]

Cycle through variants every interval seconds from start_time to end_time.

Parameters:
Return type:

None

get_active_variant_name(pose=None, time=None)[source]
Parameters:
Return type:

str

class handanim.primitives.character.TwoJointLimb(name, upper_node, lower_node, effector_pos, bend_direction=1)[source]

Bases: object

Two-bone inverse kinematics chain descriptor (e.g. upper arm + forearm).

Parameters:
name

Identifier used in Pose.ik_targets[name].

Type:

str

upper_node

Name of the upper RigNode (e.g. “upper_arm_r”).

Type:

str

lower_node

Name of the lower RigNode (e.g. “forearm_r”), which must be a child of upper_node.

Type:

str

effector_pos

Rest position of the end effector (e.g. hand/wrist or foot).

Type:

tuple[float, float]

bend_direction

+1 or -1 controlling which way the middle joint bends.

Type:

int

name: str
upper_node: str
lower_node: str
effector_pos: tuple[float, float]
bend_direction: int = 1
class handanim.primitives.character.CharacterRig(root=None, limbs=None, rest_pose=None, pivot=(0.0, 0.0), *args, **kwargs)[source]

Bases: Drawable

Articulated 2D character rig combining hierarchical RigNode objects, TwoJointLimb IK, and VariantSlot nodes.

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.

Parameters:
Return type:

RigNode

add_slot(slot_or_name, variants=None, default=None, pivot=None, *args, **kwargs)[source]

Attach a VariantSlot directly to self.root.

Parameters:
Return type:

VariantSlot

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.

Parameters:
Return type:

TwoJointLimb

capture_pose()[source]

Return a copy of the rig’s current rest pose.

Return type:

Pose

has_scheduled_variants()[source]

Return True if any VariantSlot in this rig has a non-empty time schedule.

Return type:

bool

get_node(name)[source]
Parameters:

name (str)

Return type:

RigNode

transform_point_for_node(node_name, point, pose=None)[source]

Transform a rest-space point attached to node_name into world coordinates under pose.

Parameters:
Return type:

tuple[float, float]

get_joint_world_pos(node_name, pose=None)[source]

Return the world-space position of node_name’s pivot under pose.

Parameters:
  • node_name (str)

  • pose (Pose | None)

Return type:

tuple[float, float]

get_limb_effector_world_pos(limb_name, pose=None)[source]

Return the world-space position of a TwoJointLimb’s end effector under pose.

Parameters:
  • limb_name (str)

  • pose (Pose | None)

Return type:

tuple[float, float]

resolve_pose(pose=None)[source]

Merge pose with rest_pose and solve any ik_targets into concrete joint angles.

Parameters:

pose (Pose | None)

Return type:

Pose

reach(limb_name, target_pos, base_pose=None)[source]

Return a new Pose with limb_name’s IK angles solved to reach target_pos.

Parameters:
Return type:

Pose

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

Parameters:
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.

Parameters:
  • scene (Any)

  • audio_clip (Any)

  • start_time (float)

  • mouth_slot (str)

  • open_variant (str)

  • closed_variant (str)

  • smile_variant (str | None)

  • head_node (str | None)

  • head_bob_angle (float)

  • interval (float)

  • overlay (bool)

draw_with_pose(pose=None, time=None)[source]
Parameters:
Return type:

OpsSet

draw(time=None)[source]

Provides the list of operations to be performed to draw this particular drawable object on the canvas

Parameters:

time (float | None)

Return type:

OpsSet

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

A flowchart process node: a Rectangle with a centered Text label.

position is the center of the node in world coordinates.

Parameters:
get_anchor(side='center')[source]
Parameters:

side (str)

Return type:

tuple[float, float]

get_bbox()[source]
Return type:

BoundingBox

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

A 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:
get_anchor(side='center')[source]
Parameters:

side (str)

Return type:

tuple[float, float]

get_bbox()[source]
Return type:

BoundingBox

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

An 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:
draw()[source]

Provides the list of operations to be performed to draw this particular drawable object on the canvas

Return type:

OpsSet

class handanim.primitives.flowchart.Flowchart(nodes, connectors, **kwargs)[source]

Bases: DrawableGroup

A complete flowchart assembled from FlowchartNode, FlowchartDiamond, and FlowchartConnector primitives.

Prefer constructing via Flowchart.from_dict(spec) rather than directly.

Parameters:
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).

Parameters:

spec (dict[str, Any])

Return type:

Flowchart

handanim.primitives.table

class handanim.primitives.table.TableRevealEvent(pairs)[source]

Bases: CompositeAnimationEvent

A 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)
add_to_scene(scene)[source]
Parameters:

scene (Any)

Return type:

None

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

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

get_bbox()[source]
Return type:

BoundingBox

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:
  • anim_class (type) – Any AnimationEvent subclass (e.g. SketchAnimation).

  • start_time (float) – When the first row’s animation begins, in seconds.

  • total_duration (float) – Total wall-clock span covering all rows.

  • **anim_kwargs – Forwarded to each anim_class constructor.

Returns:

TableRevealEvent whose .add_to_scene(scene) registers all pairs.

Return type:

TableRevealEvent

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:
  • anim_class (type) – Any AnimationEvent subclass (e.g. SketchAnimation).

  • start_time (float) – When the first cell’s animation begins, in seconds.

  • total_duration (float) – Total wall-clock span covering all cells.

  • **anim_kwargs – Forwarded to each anim_class constructor.

Returns:

TableRevealEvent whose .add_to_scene(scene) registers all pairs.

Return type:

TableRevealEvent

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

A 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).

Parameters:

position (tuple[float, float])

svg_doc

The parsed SVG document object from svgelements.

position

The base (x, y) offset for the SVG.

Type:

tuple[float, float]

classmethod from_svg_file(svg_file_path, *args, **kwargs)[source]

Create a VectorSVG instance from a file path

Parameters:

svg_file_path (str)

Return type:

VectorSVG

classmethod from_svg_string(svg_string, *args, **kwargs)[source]

Create a VectorSVG instance from an SVG string

Parameters:

svg_string (str)

Return type:

VectorSVG

draw()[source]

Parse SVG elements and convert them into a set of drawing operations

Return type:

OpsSet

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

A 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).

draw()[source]

Provides the list of operations to be performed to draw this particular drawable object on the canvas

Return type:

OpsSet

handanim.primitives.eraser

class handanim.primitives.eraser.Eraser(objects_to_erase, drawable_cache=None, *args, **kwargs)[source]

Bases: Drawable

A Drawable representing an eraser that can remove specified drawable objects.

Parameters:
objects_to_erase

The list of drawable objects to be erased.

Type:

List[Drawable]

drawable_cache

Cache used for calculating bounding box of objects to erase.

Type:

DrawableCache

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.

draw()[source]

Calculates the zigzag motion of the eraser

Return type:

OpsSet