handanim Package

Top-level convenience exports from handanim (see the subpackage pages for full method details):

class handanim.Scene(width=1280, height=720, fps=24, background_color=(1, 1, 1), viewport=None, narration=None, audio=None, background_music=None, music_volume=0.18, music_loop=True, sketch_sound=False, sketch_sound_volume=0.25, sketch_sound_style='chalk', eraser_sound=False, eraser_sound_volume=0.45, transition_sound=False, transition_sound_volume=0.45)[source]

Bases: object

A Scene represents an animation composition where drawables and events are managed.

Handles the creation, timeline, and rendering of animated graphics with configurable viewport, background, and frame settings. Supports creating snapshots and full video renders of animated sequences.

Parameters:
width

Width of the rendering surface in pixels.

Type:

int

height

Height of the rendering surface in pixels.

Type:

int

fps

Frames per second for video rendering.

Type:

int

background_color

RGB color for scene background.

Type:

tuple

viewport

Defines coordinate mapping between world and screen space.

Type:

Viewport

set_viewport_to_identity()[source]

Resets the viewport to an identity transformation, mapping world coordinates directly to screen coordinates.

get_viewport_bounds()[source]

Retrieves the viewport’s boundaries in world coordinates.

Returns:

A tuple containing (x_min, x_max, y_min, y_max) representing the viewport’s world coordinate boundaries.

Return type:

Tuple[float, float, float, float]

add(event, drawable=None, *, overlay=False, background=False)[source]

Adds an animation event to a drawable primitive in the scene.

Handles different scenarios including: - Self-driving drawables such as Captions, CountdownTimer, ProgressBar, or TimeDrivenDrawable - Swap(a, b, t) events (e.g. scene.add(Swap(a, b, t))) - Composite animation events (recursively adding sub-events) - Drawable groups with parallel or sequential event distribution - Single event and drawable cases

Manages event tracking, drawable caching, and object timelines.

Parameters:
  • event (AnimationEvent | Drawable) – The animation event (or self-driving drawable) to be added.

  • drawable (Drawable, optional) – The drawable primitive to apply the event to.

  • overlay (bool, optional) – If True, renders the drawable in the camera-independent foreground overlay layer.

  • background (bool, optional) – If True, renders the drawable in the camera-independent background layer.

swap(source, target, start_time=0.0, duration=0.0, easing_fun=None, *, overlay=False, background=False)[source]

Atomically hide source and show target at start_time (or cross-fade if duration > 0).

Parameters:
Return type:

None

get_current_time()[source]

Returns the end time of the latest event or beat cursor in the scene, or 0.0 if empty.

Return type:

float

wait(duration)[source]

Insert a pause of duration seconds after the current last event.

Returns the time at which the next event should start.

Usage:

scene.add(SketchAnimation(start_time=0, duration=2), rect)
t = scene.wait(1.0)  # t = 3.0
scene.add(SketchAnimation(start_time=t, duration=2), circle)
Parameters:

duration (float)

Return type:

float

beat(name='', narration=None, duration=None, start_time=None, pad_before=0.0, pad_after=0.3, transition_on_exit=None)[source]

Open a voice-driven BeatContext block for relative timeline authoring.

Usage:

with scene.beat("Intro", narration=clip1, pad_after=0.4) as b:
    b.sketch(title, at=0.0, duration=1.0)
    b.sketch(diagram, word="triangle", duration=1.5, clear_on_exit=True)
Parameters:
get_stitched_narration(output_path=None)[source]

Stitch all narration AudioClip`s attached to `scene.beat(…) blocks into a single master AudioClip.

Parameters:

output_path (str | Path | None)

add_beat_captions(**caption_kwargs)[source]

Create and attach a Captions drawable on scene.overlay from all scene.beat() narrations.

Parameters:

caption_kwargs (Any)

static place_relative(target, reference, target_anchor='center', reference_anchor='center', offset=(0.0, 0.0))[source]

Position target so that its anchor aligns with a reference drawable’s anchor.

Returns the translated target — does not mutate the original (consistent with the immutability invariant).

Parameters:
  • target (Drawable) – The drawable to reposition.

  • reference (Drawable) – The drawable to align against.

  • target_anchor (str) – Anchor name on the target (e.g. “top_left”, “center”).

  • reference_anchor (str) – Anchor name on the reference.

  • offset (tuple[float, float]) – Additional (dx, dy) offset after alignment.

Return type:

Drawable

Usage:

label = Text("hello", position=(0, 0))
label = Scene.place_relative(label, rect, "top", "bottom", offset=(0, -20))
add_camera(event)[source]

Register a CameraAnimation that controls the viewport over time.

Camera events are kept separate from drawable events and are applied per-frame in the render loop without touching any drawable’s OpsSet.

Parameters:

event – A CameraAnimation instance (or any object with an apply_to_viewport(viewport, progress) method).

Return type:

None

add_transition(transition)[source]

Register a SceneTransition (such as PageTurnTransition or PaperCrumpleTransition).

Transitions fold or crumple all world-space drawables created before transition.start_time, revealing a fresh page underneath and automatically deactivating the previous page’s world drawables once transition.end_time is reached. Overlay drawables (scene.overlay) remain unaffected.

Return type:

None

get_active_objects(t)[source]

Determines the list of object IDs that are active at a specific time point.

Calculates object visibility by toggling their active status based on their timeline. An object becomes active when its timeline reaches a time point, and its status alternates with each subsequent time point. World-space objects whose latest creation preceded a completed SceneTransition (last_shown_time < tr.start_time and t >= tr.end_time) are automatically deactivated.

Parameters:

t (float) – The time point (in seconds) to check object activity.

Returns:

A list of object IDs that are active at the given time point.

Return type:

List[str]

find_key_frames()[source]

Find the key frames that we need to calculate for the animation Key frames are the frames where an object is created or deleted

Return type:

tuple[list[float], dict[str, list[AnimationEvent]]]

get_object_event_and_progress(object_id, t, drawable_events_mapping)[source]
Parameters:
Return type:

list[tuple[AnimationEvent, float]]

get_animated_opsset_at_time(drawable_id, t, event_and_progress, drawable_events_mapping)[source]
Parameters:
Return type:

OpsSet

create_event_timeline(max_length=None)[source]

Creates a timeline of animation events and calculates the OpsSet for each frame.

This method processes all drawable events, determines active objects at each frame, and generates a list of OpsSet operations representing the animation progression.

Parameters:
  • fps (int, optional) – Frames per second for the animation. Defaults to 30.

  • max_length (Optional[float], optional) – Maximum duration of the animation. Defaults to None.

  • verbose (bool, optional) – If True, provides detailed logging during animation calculation. Defaults to False.

Returns:

A list of OpsSet operations for each frame in the animation.

Return type:

List[OpsSet]

introspect(max_length=None, safe_zone=None, check_overlaps=True)[source]

Analyze the scene layout, active drawable collisions, and platform safe zones without rendering frames.

Performs headless static inspection: - Calculates bounding boxes for all registered drawables. - Identifies objects placed outside the visible world viewport. - Checks platform UI safe zones when safe_zone=”youtube_shorts” or “youtube_landscape” is specified. - Detects unintended bounding-box overlaps between simultaneously active drawables at keyframe timestamps. - Audits event timing (creation, duration, deletion) and active intervals. - Reports warnings and errors in a machine-readable dictionary suitable for AI agents.

Returns:

dict containing duration, viewport, objects, overlaps, safe_zone_violations, warnings, and errors.

Parameters:
  • max_length (float | None)

  • safe_zone (str | None)

  • check_overlaps (bool)

Return type:

dict

render_frame(t, output_path=None, opsset=None)[source]

Render a single frame at time t (seconds) and return an (H, W, 3) uint8 RGB numpy array.

Evaluates only the requested timestamp t (unless a precomputed opsset is provided), avoiding full timeline computation for single stills. If output_path is provided, also writes the frame to disk (.png, .svg, or .pdf).

Parameters:
Return type:

ndarray

render_snapshot(output_path, frame_in_seconds, max_length=None)[source]

Render a snapshot of the animation at a specific time point as an SVG, PNG, or PDF file.

Evaluates only the requested timestamp frame_in_seconds rather than computing all frames across the full video timeline.

Parameters:
  • output_path (str) – Path to the output file (.svg, .png, or .pdf).

  • frame_in_seconds (float) – The exact time point (in seconds) to render.

  • max_length (Optional[float], optional) – Total duration of the animation. Defaults to None.

render_contact_sheet(output_path, timestamps=None, n_frames=6, cols=3, cell_width=360, safe_zone=None, max_length=None)[source]

Render multiple timestamp snapshots into a single annotated PNG grid image.

Ideal for fast LLM visual review of an entire storyboard in one image call.

Parameters:
Return type:

str

export_storyboard(n_frames, output_dir, format='svg', max_length=None)[source]

Export evenly-spaced keyframes as a storyboard.

Parameters:
  • n_frames (int) – Number of frames to export.

  • output_dir (str) – Directory to write output files.

  • format (str) – “svg” or “pdf”.

  • max_length (float | None) – Total animation duration override.

Returns:

List of output file paths.

Return type:

list[str]

render_keyframes(times, output_dir, format='svg', prefix='frame', max_length=None)[source]

Batch export snapshots at multiple timestamps.

Computes the event timeline once, then renders each requested frame.

Parameters:
  • times (list[float]) – List of timestamps (in seconds) to export.

  • output_dir (str) – Directory to write output files.

  • format (str) – “svg” or “pdf”.

  • prefix (str) – Filename prefix; files are named {prefix}_{i:03d}_{time:.2f}.{format}.

  • max_length (float | None) – Total animation duration override.

Returns:

List of output file paths.

Return type:

list[str]

render_handout(output_path, n_frames=6, times=None, max_length=None)[source]

Render a single multi-page PDF with one animation frame per page.

Either provide explicit times or let n_frames evenly-spaced keyframes be chosen automatically.

Parameters:
  • output_path (str) – Path to the output PDF file.

  • n_frames (int) – Number of evenly-spaced frames (ignored if times is given).

  • times (list[float] | None) – Explicit list of timestamps (in seconds) to render.

  • max_length (float | None) – Total animation duration override.

Returns:

The output file path.

Return type:

str

render_tikz(output_path, time=0.0, target_width_cm=12.0, max_length=None)[source]

Render a single animation frame as a standalone TikZ/LaTeX file.

Parameters:
  • output_path (str) – Path to write the .tex file.

  • time (float) – Timestamp (in seconds) to render.

  • target_width_cm (float) – Width of the tikzpicture in centimetres.

  • max_length (float | None) – Total animation duration override.

Returns:

The output file path.

Return type:

str

export_beamer(output_dir, n_frames=6, times=None, title='Handanim Slides', max_length=None, backend='cairo', target_width_cm=12.0)[source]

Export animation keyframes as a compilable Beamer/LaTeX slide deck.

Each keyframe becomes one overlay on a single frame, so the slides animate forward when presented.

With backend="cairo" (default), each keyframe is rendered as a Cairo PDF and embedded via \includegraphics.

With backend="tikz", keyframes are emitted as inline TikZ drawing commands — native LaTeX vector graphics, no external files.

Parameters:
  • output_dir (str) – Directory to write output files and the .tex file.

  • n_frames (int) – Number of evenly-spaced keyframes (ignored if times given).

  • times (list[float] | None) – Explicit list of timestamps to render.

  • title (str) – Title shown on the Beamer title page.

  • max_length (float | None) – Total animation duration override.

  • backend (str) – "cairo" for PDF-image overlays, "tikz" for native TikZ.

  • target_width_cm (float) – Width of tikzpicture (only used with backend="tikz").

Returns:

Path to the generated .tex file.

Return type:

str

set_background_music(music='marimba', volume=0.18, loop=True)[source]

Configure background theme music or audio to play (and optionally loop) in rendered videos.

Parameters:
  • music (Any) – Theme preset (“marimba”, “calm”, “upbeat”), True, AudioClip, or path to a WAV/MP3 file.

  • volume (float) – Volume multiplier for the music track (default 0.18).

  • loop (bool) – If True (default), repeats the background music across the full video duration.

Return type:

None

enable_sketch_sound(enabled=True, volume=None, style=None)[source]

Turn on/off or adjust chalk / sketch-pen drawing sounds during SketchAnimation events.

Parameters:
  • enabled (bool | float) – True / False to toggle sketch sound on or off, or a float volume multiplier (e.g. 0.15 to enable at volume 0.15, or 0.0 to turn off).

  • volume (float | None) – Optional volume multiplier (0.0 to 1.0, default 0.25). Setting volume=0 turns sound off.

  • style (str | None) – Optional drawing sound style (“chalk” or “pen”).

Return type:

None

disable_sketch_sound()[source]

Turn off automatic chalk / sketch-pen drawing sounds.

Return type:

None

set_sketch_sound(enabled=True, volume=None, style=None)[source]

Configure or toggle automatic sketch sound (alias for enable_sketch_sound).

Parameters:
Return type:

None

enable_eraser_sound(enabled=True, volume=None)[source]

Automatically play board/paper erasing sounds during Eraser animations.

Parameters:
Return type:

None

disable_eraser_sound()[source]

Turn off automatic eraser sounds.

Return type:

None

enable_transition_sound(enabled=True, volume=None)[source]

Automatically play page-turn and paper-crumple sounds during SceneTransition animations.

Parameters:
Return type:

None

disable_transition_sound()[source]

Turn off automatic scene transition sounds.

Return type:

None

extract_auto_sfx_events(include_sketch=None, include_eraser=None, include_transition=None, sketch_volume=None, sketch_style=None, eraser_volume=None, transition_volume=None)[source]

Extract non-overlapping chalk sketch, eraser, and transition SFX intervals from the scene timeline.

Parameters:
  • include_sketch (bool | float | None)

  • include_eraser (bool | float | None)

  • include_transition (bool | float | None)

  • sketch_volume (float | None)

  • sketch_style (str | None)

  • eraser_volume (float | None)

  • transition_volume (float | None)

Return type:

list[dict[str, Any]]

render(output_path, max_length=None, narration=None, background_music=None, music_volume=None, music_loop=None, sketch_sound=None, sketch_sound_volume=None, sketch_sound_style=None, eraser_sound=None, eraser_sound_volume=None, transition_sound=None, transition_sound_volume=None, sfx_events=None, *, crf=None, preset=None, tune=None, workers=1)[source]

Render the animation as a video file, optionally mixing narration, repeating background theme music, and automatic chalk/eraser/transition sound effects.

Parameters:
  • output_path (str) – Path to save the output video file.

  • max_length (Optional[float], optional) – Maximum duration of the animation. Defaults to None.

  • narration (Optional[Any], optional) – An AudioClip instance from voiceanim or path to a WAV/MP3 file.

  • background_music (Optional[Any], optional) – Theme preset (“marimba”, “calm”, “upbeat”), True, AudioClip, or path to a music file. Defaults to self.background_music.

  • music_volume (Optional[float], optional) – Background music volume multiplier.

  • music_loop (Optional[bool], optional) – Whether to repeat background music for the whole video.

  • sketch_sound (Optional[bool | float], optional) – True/False to turn automatic chalk sound on/off during SketchAnimation, or a float volume multiplier (e.g. 0.15 for quiet sketch sound, 0.0 to mute).

  • sketch_sound_volume (Optional[float], optional) – Volume multiplier (0.0 to 1.0) for sketch sounds.

  • sketch_sound_style (Optional[str], optional) – Style of sketch sound (“chalk” or “pen”).

  • eraser_sound (Optional[bool | float], optional) – If True (or positive float), adds erasing sound during Eraser.

  • eraser_sound_volume (Optional[float], optional) – Volume multiplier for eraser sounds.

  • transition_sound (Optional[bool | float], optional) – If True (or positive float), adds page-turn/crumple sound.

  • transition_sound_volume (Optional[float], optional) – Volume multiplier for transition sounds.

  • sfx_events (Optional[Sequence], optional) – Extra custom sound effect events to mix in.

  • crf (int | None)

  • preset (str | None)

  • tune (str | None)

  • workers (int)

handanim.get_cairo_backend()[source]

Return the name of the active Cairo backend (‘pycairo’ or ‘cairocffi’).

Return type:

str

class handanim.BeatContext(scene, name='', narration=None, duration=None, start_time=None, pad_before=0.0, pad_after=0.3, transition_on_exit=None)[source]

Bases: object

Context manager representing a self-contained narrative beat on a Scene timeline.

Automatically tracks the beat’s start time, derives its duration from an attached AudioClip (or explicit duration), resolves spoken word timestamps relative to the beat via b.t(“word”), and cleans up temporary beat-scoped drawables on exit via b.clear_on_exit(…).

Parameters:
  • scene (Scene)

  • name (str)

  • narration (Any)

  • duration (float | None)

  • start_time (float | None)

  • pad_before (float)

  • pad_after (float)

  • transition_on_exit (Any)

scene: Scene
name: str = ''
narration: Any = None
duration: float | None = None
start_time: float | None = None
pad_before: float = 0.0
pad_after: float = 0.3
transition_on_exit: Any = None
property start: float

Absolute start timestamp (in seconds) of this beat in the scene.

property cursor: float

Current time cursor inside this beat (updated as events are scheduled).

property end: float

Absolute end timestamp (in seconds) of this beat (before pad_after and exit cleanups).

property effective_duration: float

Total active duration of this beat in seconds.

rel(offset=0.0)[source]

Convert a beat-relative offset (in seconds) into an absolute scene timestamp.

Parameters:

offset (float)

Return type:

float

t(word=None, occurrence=1, lead_in=0.0, offset=0.0, default=0.0)[source]

Return the absolute scene timestamp when word is spoken in this beat’s narration.

If word is None, returns self.start + offset. If word is not found in self.narration, falls back to self.start + default + offset.

Parameters:
Return type:

float

word_range(word, occurrence=1)[source]

Return the absolute (start, end) scene timestamps for word in this beat.

Parameters:
Return type:

tuple[float, float]

add(event, drawable, *, overlay=False, clear_on_exit=False)[source]

Add an animation event to the scene within this beat and update the beat cursor.

Parameters:
Return type:

Drawable

sketch(drawable, at=None, *, word=None, occurrence=1, lead_in=0.08, offset=0.0, duration=1.0, relative=True, overlay=False, clear_on_exit=False, **sketch_kwargs)[source]

Schedule a SketchAnimation on drawable inside this beat.

Parameters:
Return type:

Drawable

fade_in(drawable, at=None, *, word=None, occurrence=1, lead_in=0.0, offset=0.0, duration=0.6, relative=True, overlay=False, clear_on_exit=False, **fade_kwargs)[source]

Schedule a FadeInAnimation on drawable inside this beat.

Parameters:
Return type:

Drawable

pop_in(drawable, at=None, *, word=None, occurrence=1, lead_in=0.0, offset=0.0, duration=0.45, relative=True, overlay=False, clear_on_exit=False, **pop_kwargs)[source]

Schedule a springy PopAnimation on drawable inside this beat.

Parameters:
Return type:

Drawable

show(drawable, at=0.0, *, word=None, occurrence=1, offset=0.0, relative=True, overlay=False, clear_on_exit=False)[source]

Instantly show drawable at at (default 0.0 relative to beat start).

Parameters:
Return type:

Drawable

hide(drawable, at=None, *, word=None, occurrence=1, offset=0.0, relative=True, overlay=False)[source]

Instantly hide drawable at at.

Parameters:
Return type:

Drawable

wait(duration)[source]

Advance the beat’s internal cursor by duration seconds and return the new absolute time.

Parameters:

duration (float)

Return type:

float

clear_on_exit(*drawables, duration=0.35, mode='fade', overlay=False)[source]

Register drawables to be automatically cleared when this beat finishes.

Parameters:
  • *drawables (Drawable | Sequence[Drawable]) – Drawables (or sequences of drawables) to clear at beat exit.

  • duration (float) – Duration of fade/erase cleanup (ignored for mode=”hide”).

  • mode (str) – “fade” (default FadeOutAnimation), “hide” (Hide), or “erase” (Eraser).

  • overlay (bool) – Whether the drawables belong to the overlay layer.

Return type:

None

class handanim.StrokeStyle(**kwargs)[source]

Bases: object

A class that defines the styling configurations for the strokes of the boundaries of the primitives.

Allows customization of stroke appearance including color, width, opacity, and pressure characteristics. Defaults to a black, 1-pixel wide constant pressure stroke with full opacity.

options

Raw keyword arguments passed during initialization

Type:

dict

color

RGB color tuple, defaults to black (0, 0, 0)

Type:

tuple

width

Stroke width in pixels, defaults to 1

Type:

int/float

opacity

Stroke opacity from 0-1, defaults to 1

Type:

float

stroke_pressure

Pressure mode for stroke rendering, defaults to StrokePressure.CONSTANT

Type:

StrokePressure

class handanim.SketchStyle(**kwargs)[source]

Bases: object

A class that defines the styling configurations for sketchy, hand-drawn style renderings.

bowing

Amount of bowing/waviness in lines, defaults to 1

Type:

int

max_random_offset

Maximum random offset for sketch lines, defaults to 2

Type:

int

roughness

Roughness of sketch lines, defaults to 1

Type:

int

curve_tightness

Tightness of curves, defaults to 0

Type:

int

curve_fitting

Curve fitting parameter, defaults to 0.95

Type:

float

curve_step_count

Number of steps for curve rendering, defaults to 9

Type:

int

disable_multi_stroke

Flag to disable multi-stroke rendering, defaults to False

Type:

bool

disable_font_mixture

Flag to disable font mixture, defaults to True

Type:

bool

class handanim.FillStyle(**kwargs)[source]

Bases: object

A class that defines the styling configurations for the fills of the primitives.

Allows customization of fill appearance including color, opacity, fill pattern, hachure settings, and fill weight. Defaults to a black fill with full opacity and hachure pattern.

options

Raw keyword arguments passed during initialization

Type:

dict

color

RGB color tuple, defaults to black (0, 0, 0)

Type:

tuple

opacity

Fill opacity from 0-1, defaults to 1

Type:

float

fill_pattern

Pattern for filling, defaults to “hachure”

Type:

str

hachure_angle

Angle of hachure lines in degrees, defaults to 45

Type:

int

hachure_gap

Gap between hachure lines, defaults to 4

Type:

int

hachure_line_width

Width of hachure lines, defaults to 1

Type:

int

zigzag_offset

Offset for zigzag pattern, defaults to -1

Type:

int

fill_weight

Weight/thickness of fill, defaults to 2

Type:

int

class handanim.Drawable(stroke_style=<handanim.core.styles.StrokeStyle object>, sketch_style=<handanim.core.styles.SketchStyle object>, fill_style=None, glow_dot_hint=None, id=None, *args, **kwargs)[source]

Bases: object

A base class representing a drawable object with drawing, transformation, and styling capabilities.

This class provides a standard interface for creating drawable objects that can be drawn on a canvas. Subclasses must implement the draw() method to define specific drawing operations.

Parameters:
id

A unique hexadecimal identifier for the drawable object.

Type:

str

stroke_style

Defines the stroke styling for the drawable.

Type:

StrokeStyle

sketch_style

Defines the sketch styling for the drawable.

Type:

SketchStyle

fill_style

Optional fill style for the drawable.

Type:

Optional[FillStyle]

glow_dot_hint

Optional configuration for glow dot rendering.

Type:

Dict

draw()[source]

Abstract method to generate drawing operations.

Return type:

OpsSet

translate()[source]

Creates a translated version of the drawable.

Parameters:
Return type:

TransformedDrawable

scale()[source]

Creates a scaled version of the drawable.

Parameters:
Return type:

TransformedDrawable

rotate()[source]

Creates a rotated version of the drawable.

Parameters:

angle (float)

Return type:

TransformedDrawable

draw()[source]

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

Return type:

OpsSet

translate(offset_x, offset_y)[source]

Translates the drawable object by the given offset

Parameters:
Return type:

TransformedDrawable

scale(scale_x, scale_y)[source]

Scales the drawable object by the given scale factors

Parameters:
Return type:

TransformedDrawable

rotate(angle)[source]

Rotates the drawable object by the given angle

Parameters:

angle (float)

Return type:

TransformedDrawable

get_bbox()[source]
Return type:

BoundingBox

anchor(position='center')[source]

Return a named anchor point in world coordinates.

Parameters:

position (str) – One of “center”, “top_left”, “top_right”, “bottom_left”, “bottom_right”, “top”, “bottom”, “left”, “right”.

Return type:

tuple[float, float]

align_to(x, y, anchor='center')[source]

Return a translated copy whose named anchor is placed at (x, y).

Parameters:
Return type:

TransformedDrawable

center_at(x, y)[source]

Return a translated copy whose bounding-box center is placed at (x, y).

Parameters:
Return type:

TransformedDrawable

centred(x, y)[source]

Alias for center_at(x, y).

Parameters:
Return type:

TransformedDrawable

class handanim.DrawableGroup(elements, grouping_method='parallel', *args, **kwargs)[source]

Bases: Drawable

A drawable group that manages a collection of drawable elements with specified grouping behavior.

Allows applying transformations or animations to multiple drawable objects either in parallel or series.

Parameters:
  • elements (List[Drawable]) – A list of drawable objects to be grouped.

  • grouping_method (str, optional) – Determines how animations are applied. Can be ‘parallel’ (default) or ‘series’. Defaults to ‘parallel’.

elements

The list of drawable elements in the group.

Type:

List[Drawable]

grouping_method

The method used for applying transformations.

Type:

str

draw()[source]

This is useful to apply transformations to the entire group of objects at once

Return type:

OpsSet

class handanim.AnimationEvent(type=AnimationEventType.CREATION, start_time=0.0, duration=0.0, easing_fun=None, data=None)[source]

Bases: object

Represents an animation event occurring on a scene with configurable properties.

Parameters:
  • type (AnimationEventType) – The type of animation to be performed.

  • start_time (float, optional) – The starting time point of the animation in seconds. Defaults to 0.

  • duration (float, optional) – The duration of the animation in seconds. Defaults to 0.

  • easing_fun (callable, optional) – An optional easing function to modify animation progression. Defaults to None.

  • data (dict, optional) – Additional configuration data specific to the animation type. Defaults to an empty dict.

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

subdivide(n_division)[source]

Returns subdivision of an event into n_division segments

Parameters:

n_division (int)

class handanim.AnimationEventType(*values)[source]

Bases: Enum

An enumeration representing different types of animation events.

CREATION = 'creation'
MUTATION = 'mutation'
DELETION = 'deletion'
COMPOSITE = 'composite'
class handanim.CompositeAnimationEvent(events, easing_fun=None, data=None)[source]

Bases: AnimationEvent

Represents a composite animation event that combines multiple animation events.

Parameters:
  • events (List[AnimationEvent]) – A list of animation events to be combined.

  • easing_fun (callable, optional) – An optional easing function to apply to the composite event.

  • data (dict, optional) – Additional configuration data for the composite animation event.

events

The list of animation events in the composite event.

Type:

List[AnimationEvent]

handanim.register_font(name, file_path, font_type=None, persist=False)[source]

Register a TTF, SVG 1.1 single-line, or custom JSON font for use in Text and Math.

By default (persist=False), registers the font in memory for the current Python process without modifying ~/.handanim/config.json.

Parameters:
  • name (str) – Identifier to use as font_name (e.g. “casual_hand”).

  • file_path (str | Path) – Path to the .ttf, .svg, or .json font file.

  • font_type (str | None) – One of “ttf”, “svg”, or “custom”. Inferred from suffix if omitted.

  • persist (bool) – If True, also saves the registration in ~/.handanim/config.json.

Returns:

The resolved absolute path to the registered font file.

Return type:

str

handanim.list_fonts()[source]

List all available font names (built-in and user-registered).

Return type:

list[str]

handanim.get_font_path(font_name)[source]

Return the filesystem path to a TTF or custom JSON font.

User-registered fonts may supply an absolute path in their ‘file’ field; built-in fonts are resolved via importlib.resources from handanim.fonts.

Parameters:

font_name (str)

Return type:

str

class handanim.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.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

class handanim.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.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

class handanim.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

class handanim.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.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.Square(top_left, side_length, *args, **kwargs)[source]

Bases: Rectangle

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

Bases: RoundedRectangle

Parameters:
class handanim.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.NGon(center, radius, n, *args, **kwargs)[source]

Bases: Polygon

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

class handanim.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

class handanim.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

class handanim.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

class handanim.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.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.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.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

class handanim.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

class handanim.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.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:
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

class handanim.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.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.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:
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.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:
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.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.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

class handanim.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

handanim.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.NumberLine(x_range=(-5.0, 5.0), length=400.0, position=(80.0, 500.0), tick_step=1.0, tick_size=12.0, include_ticks=True, include_numbers=True, include_arrows=True, font_size=20, label=None, stroke_style=None, sketch_style=None, **kwargs)[source]

Bases: Drawable

A hand-sketched 1D number line with ticks, optional number labels, and coordinate conversion.

In handanim’s world coordinate system (top-left origin, y downward), the number line extends horizontally from position = (x0, y0) to (x0 + length, y0).

Parameters:
n2p(value)[source]

Map a scalar number value to its world-space (x, y) point on the number line.

Parameters:

value (float)

Return type:

tuple[float, float]

p2n(point)[source]

Map a world-space point (wx, wy) back to the scalar value on the number line.

Parameters:

point (tuple[float, float])

Return type:

float

draw()[source]

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

Return type:

OpsSet

class handanim.Axes(x_range=(-5.0, 5.0), y_range=(-3.0, 3.0), width=420.0, height=280.0, position=(70.0, 220.0), x_step=1.0, y_step=1.0, tick_size=8.0, include_ticks=True, include_numbers=False, include_arrows=True, x_label=None, y_label=None, font_size=18, stroke_style=None, sketch_style=None, **kwargs)[source]

Bases: Drawable

A hand-sketched 2D Cartesian coordinate system with ticks, labels, and plotting helpers.

Maps mathematical coordinates (x, y) (where y increases upward) onto handanim’s world coordinate box anchored at position = (left, top) with size (width, height).

Parameters:
c2p(x, y)[source]

Convert mathematical coordinates (x, y) into world coordinates (wx, wy).

Parameters:
Return type:

tuple[float, float]

p2c(wx, wy)[source]

Convert world coordinates (wx, wy) into mathematical coordinates (x, y).

Parameters:
Return type:

tuple[float, float]

property origin_point: tuple[float, float]

World-space point where the x-axis and y-axis intersect (clamped to [x_range, y_range]).

plot(func, x_range=None, num_samples=120, color=(0.0, 0.0, 1.0), stroke_width=3.0, dashed=False, **kwargs)[source]

Create a FunctionGraph drawable for y = func(x) on these axes.

Parameters:
Return type:

FunctionGraph

plot_scatter(points, radius=5.5, color=(1.0, 0.0, 0.0), fill_opacity=0.85, grouping_method='parallel')[source]

Create a DrawableGroup of hand-sketched scatter dots at mathematical (x, y) coordinates.

Parameters:
Return type:

DrawableGroup

draw()[source]

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

Return type:

OpsSet

class handanim.FunctionGraph(func, axes, x_range=None, num_samples=120, color=(0.0, 0.0, 1.0), stroke_width=3.0, dashed=False, dash_length=10.0, gap_length=6.0, clip_to_axes=True, stroke_style=None, sketch_style=None, **kwargs)[source]

Bases: Drawable

A hand-sketched curve $y = f(x)$ plotted on an Axes coordinate system.

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.BarChart(values, labels=None, position=(70.0, 220.0), width=420.0, height=260.0, y_range=None, bar_colors=None, fill_opacity=0.65, fill_strategy='hachure', bar_width_ratio=0.62, show_values=True, value_suffix='', title=None, font_size=18, font_name=None, stroke_style=None, sketch_style=None, **kwargs)[source]

Bases: Drawable

A hand-sketched bar chart with category labels, value annotations, and per-bar sub-drawables.

Parameters:
axes_drawable

The L-shaped baseline and vertical axis drawable.

Type:

Drawable

bar_drawables

Individual bar (+ label/value) drawables in left-to-right order.

Type:

list[Drawable]

bars_group

A “series” DrawableGroup of bar_drawables for sequential reveal.

Type:

DrawableGroup

get_bar_top(index)[source]

Return the world-space (x, y) coordinates of the top-center of bar index.

Parameters:

index (int)

Return type:

tuple[float, float]

draw()[source]

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

Return type:

OpsSet

class handanim.LineChart(values, x_values=None, labels=None, position=(70.0, 220.0), width=420.0, height=260.0, y_range=None, color=(0.0, 0.0, 1.0), show_points=True, point_radius=5.0, title=None, font_size=18, stroke_style=None, sketch_style=None, **kwargs)[source]

Bases: Drawable

A hand-sketched line chart with data markers, optional category labels, and point coordinate lookup.

Parameters:
get_point(index)[source]

Return the world-space (wx, wy) coordinates of the index-th data point.

Parameters:

index (int)

Return type:

tuple[float, float]

draw()[source]

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

Return type:

OpsSet

class handanim.HighlightMarker(target, color=(1.0, 1.0, 0.0), opacity=0.35, padding=6.0, style='marker', passes=2, stroke_style=None, sketch_style=None, **kwargs)[source]

Bases: Drawable

A translucent chisel-tip highlighter stroke or sketchy underline over a target drawable or bbox.

Usage:

hl = HighlightMarker(key_term, color=YELLOW, opacity=0.35)
scene.add(SketchAnimation(start_time=1.0, duration=0.6), hl)
Parameters:
is_emphasis_overlay: bool = True
draw()[source]

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

Return type:

OpsSet

class handanim.CurlyBrace(target_or_p1, p2=None, direction='down', amplitude=16.0, offset=8.0, label=None, font_size=22, font_name=None, stroke_style=None, sketch_style=None, **kwargs)[source]

Bases: Drawable

A hand-drawn curly brace ({) spanning a drawable or two endpoints, with an optional label.

Parameters:
tip_point

World-space coordinates of the central point of the brace.

Type:

tuple[float, float]

label_position

Suggested anchor point for a text/math label outside the tip.

Type:

tuple[float, float]

is_emphasis_overlay: bool = True
draw()[source]

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

Return type:

OpsSet

class handanim.CalloutBubble(text, position=(100.0, 100.0), tail_target=None, width=None, height=None, padding=16.0, font_size=22, font_name=None, fill_color=(1.0, 1.0, 1.0), fill_opacity=0.92, stroke_style=None, sketch_style=None, **kwargs)[source]

Bases: Drawable

A hand-sketched speech or annotation callout bubble with a pointer tail aimed at tail_target.

Parameters:
is_emphasis_overlay: bool = True
tail_point: tuple[float, float] | None
draw()[source]

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

Return type:

OpsSet

class handanim.CrossOut(target, style='x', color=(1.0, 0.0, 0.0), width=4.2, padding=6.0, stroke_style=None, sketch_style=None, **kwargs)[source]

Bases: Drawable

A bold hand-sketched red ‘X’ or strike-through over a target drawable to debunk a misconception.

Parameters:
is_emphasis_overlay: bool = True
draw()[source]

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

Return type:

OpsSet

class handanim.TimeDrivenAnimation(drawable, start_time=0.0, duration=0.0, easing_fun=None, data=None)[source]

Bases: AnimationEvent

Animation event that delegates per-frame rendering to a TimeDrivenDrawable.

Parameters:
  • drawable (TimeDrivenDrawable)

  • start_time (float)

  • duration (float)

  • data (dict | None)

class handanim.TimeDrivenDrawable(duration=10.0, start_time=0.0, stroke_style=None, sketch_style=None, **kwargs)[source]

Bases: Drawable

Base class for self-driving drawables whose appearance depends on scene time t and [0, 1] progress.

Subclasses implement draw_at_time(t: float, progress: float) -> OpsSet and can be added directly to scene.overlay.add(widget), scene.background.add(widget), or scene.add(widget) without constructing a separate AnimationEvent.

Parameters:
draw_at_time(t, progress=None)[source]

Render the drawable’s OpsSet at scene timestamp t (in seconds).

Parameters:
Return type:

OpsSet

to_event()[source]

Create the TimeDrivenAnimation event that drives this drawable over [start_time, start_time + duration].

Return type:

TimeDrivenAnimation

draw()[source]

Render the initial state (t = start_time, progress = 0.0) for static bounds/cache inspection.

Return type:

OpsSet

class handanim.CustomTimeDrawable(render_fn, duration=10.0, start_time=0.0, **kwargs)[source]

Bases: TimeDrivenDrawable

Wraps a user callback render_fn(t: float, progress: float) -> Drawable | OpsSet as a self-driving drawable.

Ideal for studio repositories that want to build custom animated logos, watermarks, or ambient background overlays on scene.background or scene.overlay.

Parameters:
draw_at_time(t, progress=None)[source]

Render the drawable’s OpsSet at scene timestamp t (in seconds).

Parameters:
Return type:

OpsSet

class handanim.CountdownTimer(duration=60.0, start_time=0.0, position=(500.0, 48.0), radius=24.0, style='both', count_down=True, time_format='seconds', color=(0.0, 0.0, 1.0), track_color=(0.5, 0.5, 0.5), text_color=None, warn_below=10.0, warn_color=(1.0, 0.0, 0.0), font_size=16, font_name=None, stroke_width=3.0, track_opacity=0.3, stroke_style=None, sketch_style=None, **kwargs)[source]

Bases: TimeDrivenDrawable

A hand-sketched timer / countdown widget for scene.overlay or scene.background.

Supports a circular progress arc (style=”ring”), digital text readout (style=”digital”), or both (style=”both”), counting down or up over duration seconds.

Parameters:
draw_at_time(t, progress=None)[source]

Render the drawable’s OpsSet at scene timestamp t (in seconds).

Parameters:
Return type:

OpsSet

class handanim.ProgressBar(duration=60.0, start_time=0.0, position=(40.0, 965.0), width=482.5, height=8.0, direction='horizontal', color=(0.0, 0.0, 1.0), track_color=(0.5, 0.5, 0.5), track_opacity=0.25, fill_opacity=0.85, stroke_style=None, sketch_style=None, **kwargs)[source]

Bases: TimeDrivenDrawable

A hand-sketched linear progress bar for scene.overlay or scene.background.

Parameters:
draw_at_time(t, progress=None)[source]

Render the drawable’s OpsSet at scene timestamp t (in seconds).

Parameters:
Return type:

OpsSet

class handanim.BackgroundGrid(x_range=(0.0, 562.5), y_range=(0.0, 1000.0), spacing=45.0, style='grid', color=(0.72, 0.78, 0.85), opacity=0.28, line_width=1.0, roughness=0.25, stroke_style=None, sketch_style=None, **kwargs)[source]

Bases: Drawable

A subtle hand-sketched paper background (“grid”, “ruled”, or “dots”) for scene.background.

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.SketchAnimation(start_time=0.0, duration=0.0, easing_fun=None, data=None, *, wait_before_fill=None, glowing_dot=None, sound=None, sound_volume=None, sound_style=None)[source]

Bases: AnimationEvent

A class representing a sketch animation event that progressively renders drawing operations.

This animation supports partial rendering of drawing and fill operations with configurable timing and optional glowing dot effects. It allows for smooth, incremental visualization of drawing sequences.

Parameters:
wait_before_fill

Delay in seconds before starting fill animation, capped at half the total duration.

Type:

float

sound

Per-animation override to turn sketch drawing sound on (True) or off (False). When None (default), inherits the scene’s sketch_sound setting.

Type:

bool | None

sound_volume

Optional per-animation volume multiplier (0.0 to 1.0) for the sketch sound.

Type:

float | None

sound_style

Optional per-animation sound style (“chalk” or “pen”).

Type:

str | None

get_partial_sketch()[source]

Calculates a partial OpsSet representing the current sketching progress.

Parameters:
Return type:

OpsSet

apply()

Applies the sketch animation to a given OpsSet at a specific progress point.

set_sound()[source]

Enables, disables, or adjusts the volume/style of the sketch sound for this event.

Parameters:
Return type:

SketchAnimation

set_sound(enabled=True, volume=None, style=None)[source]

Turn sketch sound on or off or adjust its volume/style for this animation event.

Parameters:
Return type:

SketchAnimation

get_partial_sketch(opsset, progress)[source]

Calculate a partial OpsSet representing the sketching progress of an operation set.

Parameters:
  • OpsSet – The full drawn opsset on which to apply partial sketching

  • progress (float) – The progress of sketching, ranging from 0.0 to 1.0.

  • opsset (OpsSet)

Returns:

A new OpsSet containing the operations up to the specified progress point,

with the last operation potentially being partially completed.

Return type:

OpsSet

class handanim.FadeInAnimation(start_time=0.0, duration=0.0, easing_fun=None, data=None, initial_opacity=0.0)[source]

Bases: AnimationEvent

A class representing a fade-in animation event that gradually increases the opacity of elements.

This animation applies a progressive opacity change from 0 to 1 over a specified duration, creating a smooth fade-in effect for graphical elements.

Parameters:
  • start_time (float, optional) – The time at which the animation begins. Defaults to 0.

  • duration (float, optional) – The total duration of the animation. Defaults to 0.

  • easing_fun (callable, optional) – An optional function to modify the animation’s progress curve. Defaults to None.

  • data (dict, optional) – Additional data associated with the animation. Defaults to None.

  • initial_opacity (float)

class handanim.FadeOutAnimation(start_time=0.0, duration=0.0, easing_fun=None, data=None)[source]

Bases: FadeInAnimation

A class representing a fade-out animation event that gradually decreases the opacity of elements.

This animation applies a progressive opacity change from 1 to 0 over a specified duration, creating a smooth fade-out effect for graphical elements.

Parameters:
  • start_time (float, optional) – The time at which the animation begins. Defaults to 0.

  • duration (float, optional) – The total duration of the animation. Defaults to 0.

  • easing_fun (callable, optional) – An optional function to modify the animation’s progress curve. Defaults to None.

  • data (dict, optional) – Additional data associated with the animation. Defaults to None.

class handanim.ZoomInAnimation(start_time=0.0, duration=0.0, easing_fun=None, data=None)[source]

Bases: AnimationEvent

A class representing a zoom-in animation event that scales an OpsSet progressively.

This animation scales the operations set from its original size to a larger size based on the provided progress value. It is typically used for creating or expanding visual elements.

Parameters:
  • start_time (int, optional) – The start time of the animation. Defaults to 0.

  • duration (int, optional) – The duration of the animation. Defaults to 0.

  • easing_fun (callable, optional) – An optional easing function to modify the animation progress. Defaults to None.

  • data (Any, optional) – Additional data associated with the animation. Defaults to None.

class handanim.ZoomOutAnimation(start_time=0.0, duration=0.0, easing_fun=None, data=None)[source]

Bases: ZoomInAnimation

A class representing a zoom-out animation event that scales an OpsSet progressively.

This animation scales the operations set from its current size to a smaller size based on the provided progress value. It is typically used for shrinking or removing visual elements.

Parameters:
  • start_time (int, optional) – The start time of the animation. Defaults to 0.

  • duration (int, optional) – The duration of the animation. Defaults to 0.

  • easing_fun (callable, optional) – An optional easing function to modify the animation progress. Defaults to None.

  • data (Any, optional) – Additional data associated with the animation. Defaults to None.

class handanim.PopAnimation(start_time=0.0, duration=0.32, overshoot=1.9, easing_fun=None, data=None)[source]

Bases: ZoomInAnimation

Zoom-in animation with an overshoot ‘pop’ easing (ease_out_back).

Parameters:
class handanim.MoveBy(dx=0.0, dy=0.0, start_time=0.0, duration=0.0, easing_fun=None, data=None, *, offset=None)[source]

Bases: AnimationEvent

Translate an OpsSet by a relative (dx, dy) offset over duration seconds.

Parameters:
handanim.TranslateByAnimation

alias of MoveBy

class handanim.TranslateFromAnimation(start_time=0, duration=0, easing_fun=None, data=None)[source]

Bases: TranslateToAnimation

A class representing a translate from a point animation event.

This animation translates an OpsSet from a specified point to its current center of gravity over the course of the animation’s duration, using an optional easing function.

Inherits from TranslateToAnimation and reverses the progress to achieve the “from” translation effect.

Parameters:
  • start_time (float, optional) – The start time of the animation. Defaults to 0.

  • duration (float, optional) – The duration of the animation. Defaults to 0.

  • easing_fun (callable, optional) – An optional easing function to modify animation progress. Defaults to None.

  • data (dict, optional) – A dictionary containing animation data, including the starting ‘point’. Defaults to None.

apply()

Applies the translation from the specified point to the OpsSet’s center of gravity.

class handanim.TranslateToAnimation(start_time=0.0, duration=0.0, easing_fun=None, data=None)[source]

Bases: AnimationEvent

A class representing a translate to a point animation event.

This animation translates an OpsSet from its current center of gravity to a specified point over the course of the animation’s duration, using an optional easing function.

Parameters:
  • start_time (float, optional) – The start time of the animation. Defaults to 0.

  • duration (float, optional) – The duration of the animation. Defaults to 0.

  • easing_fun (callable, optional) – An optional easing function to modify animation progress. Defaults to None.

  • data (dict, optional) – A dictionary containing animation data, including the target ‘point’. Defaults to None.

_opsset_apply()[source]

Calculates and applies the translation of the OpsSet.

apply()

Applies the translation to the given OpsSet at the specified progress.

class handanim.RotateAnimation(start_time=0.0, duration=0.0, easing_fun=None, data=None)[source]

Bases: AnimationEvent

Animates a rotation of an OpsSet from 0 to angle degrees over the duration.

The rotation is applied around the center of gravity by default, or around a fixed center point if provided in data.

Parameters:
  • start_time – When the animation begins (seconds).

  • duration – Length of the animation (seconds).

  • easing_fun – Optional easing function.

  • data – Dict with optional keys: - “angle” (float): Total rotation angle in degrees. Default 360. - “center” (tuple[float, float]): Fixed pivot point. Default: center of gravity.

class handanim.ColorTransitionAnimation(start_time=0.0, duration=0.0, easing_fun=None, data=None)[source]

Bases: AnimationEvent

Interpolates every SET_PEN color in an OpsSet from start_color to end_color.

At progress=0 all strokes are rendered with start_color; at progress=1 they use end_color. The fill color (if present) is interpolated identically.

Parameters:
  • start_time – When the animation begins (seconds).

  • duration – Length of the animation (seconds).

  • easing_fun – Optional easing function.

  • data – Dict with keys: - “start_color” (tuple[float,float,float]): RGB at progress 0. Required. - “end_color” (tuple[float,float,float]): RGB at progress 1. Required.

class handanim.CameraAnimation(start_time=0.0, duration=0.0, easing_fun=None, data=None)[source]

Bases: AnimationEvent

Animates the Scene viewport (pan and/or zoom) over time.

Instead of touching any drawable’s OpsSet, this animation changes the world ranges that the Viewport maps to the screen — the “camera” moves, not the content.

Parameters:
  • start_time – When the animation begins (seconds).

  • duration – Length of the animation (seconds).

  • easing_fun – Optional easing function applied to progress.

  • data –

    Dict with optional keys:

    • "from_xrange" (tuple[float, float]): World x range at progress=0. Defaults to wherever the camera currently is.

    • "from_yrange" (tuple[float, float]): World y range at progress=0. Defaults to wherever the camera currently is.

    • "to_xrange" (tuple[float, float]): World x range at progress=1. Defaults to from_xrange (no movement on x).

    • "to_yrange" (tuple[float, float]): World y range at progress=1. Defaults to from_yrange (no movement on y).

Usage:

scene.add_camera(CameraAnimation(
    start_time=5, duration=3,
    data={
        "to_xrange": (400, 800),
        "to_yrange": (200, 600),
    }
))
apply_to_viewport(current, progress)[source]

Return a new Viewport interpolated toward the target world ranges.

Parameters:
  • current (Viewport) – The viewport state immediately before this event (used as the from_* default when not explicitly specified).

  • progress (float) – Animation progress from 0.0 to 1.0.

Returns:

A new Viewport instance with interpolated world ranges.

Return type:

Viewport

class handanim.MorphAnimation(target_drawable=None, start_time=0.0, duration=1.0, easing_fun=None, points_per_subpath=24, data=None)[source]

Bases: AnimationEvent

Smoothly morphs the stroke paths, colors, and widths of a drawable into target.

Usage:

scene.add(SketchAnimation(start_time=0.0, duration=1.5), circle)
scene.add(MorphAnimation(target_drawable=square, start_time=2.0, duration=1.5), circle)
Parameters:
class handanim.PoseAnimation(rig=None, to_pose=None, from_pose=None, start_time=0.0, duration=0.0, keyframes=None, easing_fun=None, data=None)[source]

Bases: AnimationEvent

Animates a CharacterRig between poses by blending joint angles, offsets, scales, and IK targets.

Supports both two-pose transitions (from_pose -> to_pose) and multi-keyframe sequences (keyframes=[(t0, pose0), (t1, pose1), …]).

Parameters:
classmethod from_keyframes(rig, keyframes, easing_fun=None)[source]

Create a PoseAnimation from a sequence of (timestamp, Pose) keyframes.

Parameters:
Return type:

PoseAnimation

get_pose_at_progress(raw_progress)[source]

Compute the blended Pose and scene timestamp at raw_progress in [0, 1].

Parameters:

raw_progress (float)

Return type:

tuple[Pose, float]

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.SceneTransition(start_time=0.0, duration=1.0, easing_fun=<function ease_in_out_cubic>, data=None)[source]

Bases: AnimationEvent

Base class for scene-level page transitions (PageTurnTransition, PaperCrumpleTransition).

When added to a Scene via scene.add_transition(transition) or scene.add(transition):

  • All world drawables created before transition.start_time belong to the outgoing page and are automatically deactivated at transition.end_time.

  • Any world drawables created at or after transition.start_time belong to the newly revealed page underneath.

  • Camera-invariant scene.overlay drawables (e.g. Captions) remain untouched above the page.

Parameters:
sfx_type: str = 'page_turn'
apply_transition(outgoing_ops, incoming_ops, raw_progress, viewport, background_color=(1.0, 1.0, 1.0))[source]

Compose the outgoing and incoming page OpsSet`s at `raw_progress in [0, 1].

Parameters:
Return type:

OpsSet

class handanim.PageTurnTransition(start_time=0.0, duration=1.0, direction='right_to_left', bleed_through=0.16, flap_color=None, border_color=(0.32, 0.3, 0.27), shadow_opacity=0.14, easing_fun=<function ease_in_out_cubic>, data=None)[source]

Bases: SceneTransition

Folds and turns the current drawing sheet across the board to reveal the next page.

Supported direction values: - "right_to_left" (default): Lifts the right side of the paper and folds it left. - "left_to_right": Lifts the left side of the paper and folds it right. - "bottom_right" (or "right_corner_to_left_corner"): Peels the bottom-right corner diagonally across to top-left. - "bottom_left" (or "left_corner_to_right_corner"): Peels the bottom-left corner diagonally across to top-right. - "top_right": Peels the top-right corner diagonally across to bottom-left. - "top_left": Peels the top-left corner diagonally across to bottom-right. - "bottom_to_top": Flips the bottom edge of the notepad upward. - "top_to_bottom": Flips the top edge downward.

Parameters:
sfx_type: str = 'page_turn'
VALID_DIRECTIONS = {'bottom_left', 'bottom_right', 'bottom_to_top', 'left_corner_to_right_corner', 'left_to_right', 'right_corner_to_left_corner', 'right_to_left', 'top_left', 'top_right', 'top_to_bottom'}
apply_transition(outgoing_ops, incoming_ops, raw_progress, viewport, background_color=(1.0, 1.0, 1.0))[source]

Compose the outgoing and incoming page OpsSet`s at `raw_progress in [0, 1].

Parameters:
Return type:

OpsSet

class handanim.PaperCrumpleTransition(start_time=0.0, duration=1.0, direction='right', seed=42, paper_color=None, border_color=(0.32, 0.3, 0.27), easing_fun=<function ease_in_out_cubic>, data=None)[source]

Bases: SceneTransition

Crumples the current sheet of paper into a jagged paper ball and tosses it off to the side.

Supported direction values: - "right" (default): Crumples toward center and tosses off the right edge. - "left": Crumples toward center and tosses off the left edge. - "top_right", "bottom_right", "top_left", "bottom_left"

Parameters:
sfx_type: str = 'crumple'
VALID_DIRECTIONS = {'bottom_left', 'bottom_right', 'left', 'right', 'top_left', 'top_right'}
apply_transition(outgoing_ops, incoming_ops, raw_progress, viewport, background_color=(1.0, 1.0, 1.0))[source]

Compose the outgoing and incoming page OpsSet`s at `raw_progress in [0, 1].

Parameters:
Return type:

OpsSet

class handanim.Show(start_time=0.0, duration=0.0, easing_fun=None, data=None)[source]

Bases: AnimationEvent

Instantly makes a drawable visible at start_time, restoring its original opacity.

Useful for placing hooks on screen at frame 0 (Show(0)) or toggling blinks, mouth shapes, and labels back on after Hide or FadeOutAnimation.

Parameters:
class handanim.Hide(start_time=0.0, duration=0.0, easing_fun=None, data=None)[source]

Bases: AnimationEvent

Instantly hides a drawable at start_time.

Parameters:
class handanim.Swap(source, target, start_time=0.0, duration=0.0, easing_fun=None, data=None)[source]

Bases: AnimationEvent

Atomically swaps source out and target in at start_time.

If duration == 0.0 (default), performs an instant Hide(start_time) on source and Show(start_time) on target. If duration > 0.0, cross-fades between them.

Usage:

scene.add(Swap(closed_mouth, open_mouth, 1.2))
# or
scene.swap(closed_mouth, open_mouth, 1.2)
Parameters:
handanim.ShowAnimation

alias of Show

handanim.HideAnimation

alias of Hide

handanim.SwapAnimation

alias of Swap

handanim.linear(t)[source]

Linear identity easing: f(t) = t.

Parameters:

t (float)

Return type:

float

handanim.ease_in_quad(t)[source]

Quadratic ease-in: f(t) = t^2.

Parameters:

t (float)

Return type:

float

handanim.ease_out_quad(t)[source]

Quadratic ease-out: f(t) = 1 - (1 - t)^2.

Parameters:

t (float)

Return type:

float

handanim.ease_in_out_quad(t)[source]

Quadratic ease-in-out.

Parameters:

t (float)

Return type:

float

handanim.ease_in_cubic(t)[source]

Cubic ease-in: f(t) = t^3.

Parameters:

t (float)

Return type:

float

handanim.ease_out_cubic(t)[source]

Cubic ease-out: f(t) = 1 - (1 - t)^3.

Parameters:

t (float)

Return type:

float

handanim.ease_in_out_cubic(t)[source]

Cubic ease-in-out: accelerates to midpoint then decelerates smoothly.

Parameters:

t (float)

Return type:

float

handanim.ease_in_out(t)

Cubic ease-in-out: accelerates to midpoint then decelerates smoothly.

Parameters:

t (float)

Return type:

float

handanim.ease_in_back(t, overshoot=1.70158)[source]

Back ease-in: pulls back slightly before accelerating forward.

Parameters:
Return type:

float

handanim.ease_out_back(t, overshoot=1.9)[source]

Overshoot ‘pop’ ease-out: overshoots 1.0 slightly then settles back to 1.0.

Parameters:
Return type:

float

handanim.ease_in_out_back(t, overshoot=1.70158)[source]

Symmetric back ease-in-out with slight pull-back and overshoot.

Parameters:
Return type:

float

handanim.ease_out_elastic(t)[source]

Elastic spring ease-out.

Parameters:

t (float)

Return type:

float

handanim.ease_out_bounce(t)[source]

Bounce ease-out.

Parameters:

t (float)

Return type:

float

Subpackages

  • handanim.core Package — Scene, Drawable, OpsSet, AnimationEvent, Styles, Viewport, Cache, and TikZRenderer

  • handanim.primitives Package — Geometric shapes, Arrows, Text, Math, Captions, CharacterRig, Flowchart, Table, VectorSVG, RasterImage, and Eraser

  • handanim.animations Package — Sketch, Fade, Visibility (Show/Hide/Swap), Easing (PopAnimation), Translate, Rotate, Zoom, ColorTransition, Camera, and PoseAnimation

  • handanim.stylings & utils Package — Color palettes, Font registry (register_font), Fill patterns, Stroke pressure, and Geometry/Humanize utilities