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:
objectA 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:
- height
Height of the rendering surface in pixels.
- Type:
- fps
Frames per second for video rendering.
- Type:
- background_color
RGB color for scene background.
- Type:
- viewport
Defines coordinate mapping between world and screen space.
- Type:
- 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.
- 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).
- 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:
- 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)
- 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)
- get_stitched_narration(output_path=None)[source]
Stitch all narration AudioClip`s attached to `scene.beat(…) blocks into a single master AudioClip.
- 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:
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.
- 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
- get_object_event_and_progress(object_id, t, drawable_events_mapping)[source]
- Parameters:
- Return type:
- get_animated_opsset_at_time(drawable_id, t, event_and_progress, drawable_events_mapping)[source]
- 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:
- 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.
- 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).
- 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.
- 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.
- export_storyboard(n_frames, output_dir, format='svg', max_length=None)[source]
Export evenly-spaced keyframes as a storyboard.
- 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:
- Returns:
List of output file paths.
- Return type:
- 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:
- Returns:
The output file path.
- Return type:
- 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.
- 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:
- 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.
- 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).
- enable_eraser_sound(enabled=True, volume=None)[source]
Automatically play board/paper erasing sounds during Eraser animations.
- 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.
- 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.
- 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:
- 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:
objectContext 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 = 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.
- 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.
- word_range(word, occurrence=1)[source]
Return the absolute (start, end) scene timestamps for word in this beat.
- 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:
event (AnimationEvent)
drawable (Drawable)
overlay (bool)
clear_on_exit (bool)
- Return type:
- 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.
- 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.
- 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.
- 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).
- hide(drawable, at=None, *, word=None, occurrence=1, offset=0.0, relative=True, overlay=False)[source]
Instantly hide drawable at at.
- wait(duration)[source]
Advance the beat’s internal cursor by duration seconds and return the new absolute time.
- 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:
objectA 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:
- color
RGB color tuple, defaults to black (0, 0, 0)
- Type:
- width
Stroke width in pixels, defaults to 1
- Type:
int/float
- opacity
Stroke opacity from 0-1, defaults to 1
- Type:
- stroke_pressure
Pressure mode for stroke rendering, defaults to StrokePressure.CONSTANT
- Type:
- class handanim.SketchStyle(**kwargs)[source]
Bases:
objectA class that defines the styling configurations for sketchy, hand-drawn style renderings.
- bowing
Amount of bowing/waviness in lines, defaults to 1
- Type:
- max_random_offset
Maximum random offset for sketch lines, defaults to 2
- Type:
- roughness
Roughness of sketch lines, defaults to 1
- Type:
- curve_tightness
Tightness of curves, defaults to 0
- Type:
- curve_fitting
Curve fitting parameter, defaults to 0.95
- Type:
- curve_step_count
Number of steps for curve rendering, defaults to 9
- Type:
- disable_multi_stroke
Flag to disable multi-stroke rendering, defaults to False
- Type:
- disable_font_mixture
Flag to disable font mixture, defaults to True
- Type:
- class handanim.FillStyle(**kwargs)[source]
Bases:
objectA 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:
- color
RGB color tuple, defaults to black (0, 0, 0)
- Type:
- opacity
Fill opacity from 0-1, defaults to 1
- Type:
- fill_pattern
Pattern for filling, defaults to “hachure”
- Type:
- hachure_angle
Angle of hachure lines in degrees, defaults to 45
- Type:
- hachure_gap
Gap between hachure lines, defaults to 4
- Type:
- hachure_line_width
Width of hachure lines, defaults to 1
- Type:
- zigzag_offset
Offset for zigzag pattern, defaults to -1
- Type:
- fill_weight
Weight/thickness of fill, defaults to 2
- Type:
- 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:
objectA 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:
stroke_style (StrokeStyle)
sketch_style (SketchStyle)
fill_style (FillStyle | None)
id (str | None)
- id
A unique hexadecimal identifier for the drawable object.
- Type:
- stroke_style
Defines the stroke styling for the drawable.
- Type:
- sketch_style
Defines the sketch styling for the drawable.
- Type:
- fill_style
Optional fill style for the drawable.
- Type:
Optional[FillStyle]
- glow_dot_hint
Optional configuration for glow dot rendering.
- Type:
Dict
- translate()[source]
Creates a translated version of the drawable.
- Parameters:
- Return type:
- scale()[source]
Creates a scaled version of the drawable.
- Parameters:
- Return type:
- draw()[source]
Provides the list of operations to be performed to draw this particular drawable object on the canvas
- Return type:
- translate(offset_x, offset_y)[source]
Translates the drawable object by the given offset
- Parameters:
- Return type:
- scale(scale_x, scale_y)[source]
Scales the drawable object by the given scale factors
- Parameters:
- Return type:
- rotate(angle)[source]
Rotates the drawable object by the given angle
- Parameters:
angle (float)
- Return type:
- get_bbox()[source]
- Return type:
- anchor(position='center')[source]
Return a named anchor point in world coordinates.
- align_to(x, y, anchor='center')[source]
Return a translated copy whose named anchor is placed at (x, y).
- Parameters:
- Return type:
- center_at(x, y)[source]
Return a translated copy whose bounding-box center is placed at (x, y).
- Parameters:
- Return type:
- centred(x, y)[source]
Alias for center_at(x, y).
- Parameters:
- Return type:
- class handanim.DrawableGroup(elements, grouping_method='parallel', *args, **kwargs)[source]
Bases:
DrawableA 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
The list of drawable elements in the group.
- Type:
List[Drawable]
- grouping_method
The method used for applying transformations.
- Type:
- class handanim.AnimationEvent(type=AnimationEventType.CREATION, start_time=0.0, duration=0.0, easing_fun=None, data=None)[source]
Bases:
objectRepresents 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.
- class handanim.AnimationEventType(*values)[source]
Bases:
EnumAn 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:
AnimationEventRepresents 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:
- handanim.list_fonts()[source]
List all available font names (built-in and user-registered).
- 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.
- class handanim.Line(start, end, *args, **kwargs)[source]
Bases:
DrawableA drawable line primitive that generates hand-drawn style lines with randomized jitter and bowing effects.
Supports customizable stroke and sketch styles, with options for line curvature, roughness, and multiple line passes to create a hand-drawn appearance. Allows for optional stroke pressure variations and provides methods to draw single or overlapping lines.
- start
Starting point coordinates of the line
- Type:
np.ndarray
- end
Ending point coordinates of the line
- Type:
np.ndarray
- draw_single_line(opsset, move=False, overlay=False)[source]
- class handanim.LinearPath(points, close=False, *args, **kwargs)[source]
Bases:
DrawableA drawable linear path that connects a series of points, with optional closing of the path.
- close
Whether to connect the last point back to the first point. Defaults to False.
- Type:
bool, optional
- Raises:
ValueError – If fewer than two points are provided.
- Parameters:
The path is drawn by creating Line objects between consecutive points, with optional path closure if specified.
- 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:
- class handanim.Curve(points, *args, **kwargs)[source]
Bases:
DrawableA class representing a curve that can be drawn with a sketchy, hand-drawn style.
Allows creating curves with multiple points, supporting various drawing techniques including single line, quadratic, and more complex multi-point curves with randomization to simulate hand-drawn appearance.
- points
List of points defining the curve’s shape.
- Type:
List[np.ndarray]
- draw_single_curve(opsset, points=None, close_point=None)[source]
Draws a single human style sketchy curve
- draw_single_curve_with_randomization(opsset, points=None, offset=1.0)[source]
Draw a single human style sketchy curve with random derivations
- class handanim.Rectangle(top_left, width, height, *args, **kwargs)[source]
Bases:
PolygonA Rectangle class representing a rectangular polygon shape.
This class creates a rectangle by specifying its top-left corner coordinates, width, and height. It inherits from the Polygon class and generates the four vertices of the rectangle automatically.
- Parameters:
- get_bbox()[source]
- Return type:
- class handanim.RoundedRectangle(top_left, width, height, border_radius=0.1, *args, **kwargs)[source]
Bases:
Drawable- get_bbox()[source]
- Return type:
- class handanim.RoundedSquare(top_left, side_length, border_radius=0.1, *args, **kwargs)[source]
Bases:
RoundedRectangle
- class handanim.Polygon(points, *args, **kwargs)[source]
Bases:
DrawableA Polygon class representing a drawable polygon shape.
This class allows creating polygons with a list of points, drawing them with optional stroke and fill styles. It ensures the polygon has at least three points and can render the polygon using a closed linear path with optional filling.
- Raises:
ValueError – If fewer than three points are provided.
- Parameters:
- class handanim.Ellipse(center, width, height, *args, **kwargs)[source]
Bases:
DrawableA drawable ellipse primitive with sketchy rendering capabilities.
Supports customizable center, width, height, and sketch-style rendering with optional multi-stroke and roughness effects. Allows for generating ellipses with randomized point generation and stroke variations.
- center
The center point of the ellipse
- Type:
np.ndarray
- width
The width of the ellipse
- Type:
- height
The height of the ellipse
- Type:
- class handanim.Circle(center, radius, *args, **kwargs)[source]
Bases:
EllipseA specialized Ellipse where the x and y radii are equal, creating a perfect circle.
- class handanim.Text(text, position=(0.0, 0.0), font_size=12, *args, **kwargs)[source]
Bases:
DrawableA Drawable text primitive that renders text using single-line or outline font glyphs.
Supports TTF fonts (type=”ttf”), open-path SVG 1.1 single-line plotter fonts (type=”svg”, e.g. “casual_hand”, “blueprint_sans”, “architect_hand”), custom skeletonized JSON fonts (type=”custom”), and Hershey stroke fonts (type=”hershey”), plus built-in open-stroke fallbacks for symbols like ₹.
- get_random_font_choice()[source]
Return (font_choice, font_path_or_id) for the resolved font.
- get_glyph_strokes(char)[source]
Return (glyph_opsset, advance_width) for char in world units.
- get_glyph_space()[source]
Return (space_width, glyph_scale) in world units.
- wrap(bbox, line_height_factor=1.5)[source]
Pre-compute line breaks so that no line of text exceeds bbox.width.
- Parameters:
bbox (BoundingBox)
line_height_factor (float)
- autofit(bbox)[source]
- Parameters:
bbox (BoundingBox)
- class handanim.Math(tex_expression, position, font_size=12, font_name='feasibly', *args, **kwargs)[source]
Bases:
DrawableA Drawable class for rendering mathematical expressions using TeX notation.
Parses a TeX expression via matplotlib’s MathTextParser and renders individual glyphs using the specified font backend.
- tex_expression
The TeX expression to render.
- position
Top-left anchor (x, y) for the rendered expression.
- font_size
Logical font size; the base unit is 10 (scale_factor = font_size / 10).
- font_name
Font backend to use (see stylings/fonts.py).
- load_font()[source]
- Return type:
None
- standard_glyph_opsset(unicode, font_size)[source]
- custom_glyph_opsset(unicode, font_size)[source]
- hershey_glyph_opsset(unicode, font_size)[source]
- get_glyph_opsset(unicode, font_size)[source]
- class handanim.Eraser(objects_to_erase, drawable_cache=None, *args, **kwargs)[source]
Bases:
DrawableA Drawable representing an eraser that can remove specified drawable objects.
- Parameters:
drawable_cache (DrawableCache | None)
- 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:
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.
- class handanim.VectorSVG(svg_doc, position=(0, 0), *args, **kwargs)[source]
Bases:
DrawableA drawable class that accepts an SVG document and renders it as a Drawable as close to the original SVG as possible.
Note
This feature was contributed by Hamd Waseem (https://github.com/hamdivazim).
- svg_doc
The parsed SVG document object from svgelements.
- classmethod from_svg_file(svg_file_path, *args, **kwargs)[source]
Create a VectorSVG instance from a file path
- classmethod from_svg_string(svg_string, *args, **kwargs)[source]
Create a VectorSVG instance from an SVG string
- 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:
DrawableGroupA flowchart process node: a Rectangle with a centered Text label.
position is the center of the node in world coordinates.
- Parameters:
- get_bbox()[source]
- Return type:
- 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:
DrawableGroupA flowchart decision node: a diamond polygon with a centered Text label.
position is the center. size = (width, height) of the diamond’s bounding box.
- Parameters:
- get_bbox()[source]
- Return type:
- 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:
DrawableAn auto-routed arrow between two flowchart nodes.
Computes an elbow route from from_node.get_anchor(from_side) to to_node.get_anchor(to_side) at draw time so that moving a node automatically updates the connector without re-construction.
For straight lines (same axis, opposing sides, perfectly aligned), a single Arrow is drawn. Otherwise an L-shaped elbow is used: the connector exits from_node in the from_side direction, turns once at the midpoint, then arrives at to_node from the to_side direction.
- Parameters:
from_node (FlowchartNode | FlowchartDiamond)
to_node (FlowchartNode | FlowchartDiamond)
from_side (str)
to_side (str)
label (str | None)
label_font_size (int)
arrow_head_type (str)
arrow_head_size (float)
arrow_head_angle (float)
- class handanim.Flowchart(nodes, connectors, **kwargs)[source]
Bases:
DrawableGroupA complete flowchart assembled from FlowchartNode, FlowchartDiamond, and FlowchartConnector primitives.
Prefer constructing via Flowchart.from_dict(spec) rather than directly.
- Parameters:
nodes (list[DrawableGroup])
connectors (list[FlowchartConnector])
- classmethod from_dict(spec, **kwargs)[source]
Build a Flowchart from a declarative spec dict.
Expected format:
{ "nodes": [ { "id": "start", "type": "node", # "node" (default) or "diamond" "label": "Start", "position": [100, 50], "size": [100, 40], # optional "font_size": 12, # optional }, ... ], "edges": [ { "from": "start", "to": "decision", "from_side": "bottom", # optional, default "bottom" "to_side": "top", # optional, default "top" "label": "Yes", # optional edge label }, ... ], }
Additional keys in each node or edge dict are forwarded as keyword arguments to the underlying primitive (e.g. stroke_style, fill_style).
- 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:
DrawableGroupA grid of Rectangle + Text cells with optional header-row styling.
Each cell is a DrawableGroup([rect, text]) stored in self.cells[row][col]. Row groups (self.row_groups[r]) contain the leaf rect/text drawables for all cells in that row — they are kept flat (no nested DrawableGroups) so that group-level scene animations apply correctly.
The Table itself is a flat parallel DrawableGroup of all leaf drawables, so scene.add(event, table) animates every cell simultaneously.
- Parameters:
top_left (tuple[float, float]) – (x, y) world coordinates of the table’s top-left corner.
n_rows (int) – Total rows, including the header row if headers is provided.
n_cols (int) – Number of columns.
cell_width (float) – Width of each cell in world units.
cell_height (float) – Height of each cell in world units.
data (list[list[str]] | None) – 2-D list of cell strings, indexed [row][col]. Rows with a header start at data[0] = row 1 of the grid. Missing entries default to “”.
headers (list[str] | None) – Column header strings for row 0. If provided, row 0 uses header_stroke_style / header_fill_style instead of the defaults.
cell_font_size (int) – Font size for data cells.
header_font_size (int) – Font size for header cells.
stroke_style (StrokeStyle) – Stroke style for data cells.
sketch_style (SketchStyle) – Sketch style shared by all cells.
fill_style (FillStyle | None) – Fill style for data cells (None = no fill).
header_stroke_style (StrokeStyle | None) – Override stroke style for header cells.
header_fill_style (FillStyle | None) – Override fill style for header cells.
font_name (str | None)
text_align (str)
- get_bbox()[source]
- Return type:
- animate_by_row(anim_class, start_time=0.0, total_duration=1.0, **anim_kwargs)[source]
Build a staggered row-reveal animation.
Each row gets an equal slice of total_duration, starting after the previous row’s slice begins. All cells in a row animate in parallel.
- Parameters:
- Returns:
TableRevealEvent whose .add_to_scene(scene) registers all pairs.
- Return type:
- animate_by_cell(anim_class, start_time=0.0, total_duration=1.0, **anim_kwargs)[source]
Build a staggered cell-reveal animation in row-major order.
Each cell gets an equal slice of total_duration. Both the rect and the text inside a cell animate together (the cell’s DrawableGroup is the target).
- Parameters:
- Returns:
TableRevealEvent whose .add_to_scene(scene) registers all pairs.
- Return type:
- class handanim.TableRevealEvent(pairs)[source]
Bases:
CompositeAnimationEventA CompositeAnimationEvent that pairs each sub-event with its target drawable.
Returned by Table.animate_by_row() and Table.animate_by_cell(). Because Scene.add() always requires an explicit drawable, callers must unpack these pairs themselves — use add_to_scene() as a one-liner convenience.
- Parameters:
pairs (list[tuple[Any, DrawableGroup]])
- pairs
List of (AnimationEvent, DrawableGroup) in reveal order.
Usage:
reveal = table.animate_by_row(SketchAnimation, start_time=0, total_duration=3) reveal.add_to_scene(scene) # or inspect and filter manually: for event, drawable in reveal.pairs: scene.add(event, drawable)
- class handanim.Captions(clip, words_per_chunk=3, highlight=(1.0, 0.0, 0.0), color=(0.0, 0.0, 0.0), y=1590.0, x=None, font_size=48, font_name=None, align='center', word_spacing=None, max_width=960.0, start_time=0.0, max_hold_gap=0.25, stroke_style=None, sketch_style=None, highlight_stroke_width=None, speaker_colors=None, speaker_highlights=None, secondary_highlight=None, highlight_numbers=False, background_color=None, background_opacity=0.85, background_padding=14.0, **kwargs)[source]
Bases:
DrawableWord-timed narration captions rendered as a single drawable + single animation event.
Groups spoken words from clip into chunks of words_per_chunk, pre-caches base and highlighted OpsSet`s for each word, and highlights the active word at any timestamp `t.
Usage:
captions = Captions(clip, words_per_chunk=3, highlight=RED, y=1590) scene.overlay.add(captions)
- Parameters:
clip (Any)
words_per_chunk (int)
y (float)
x (float | None)
font_size (int)
font_name (str | None)
align (str)
word_spacing (float | None)
max_width (float | None)
start_time (float)
max_hold_gap (float)
stroke_style (StrokeStyle | None)
sketch_style (SketchStyle | None)
highlight_stroke_width (float | None)
speaker_colors (dict[str, tuple[float, float, float]] | None)
speaker_highlights (dict[str, tuple[float, float, float]] | None)
highlight_numbers (bool)
background_opacity (float)
background_padding (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.
- draw_at_time(t)[source]
Return the OpsSet for the caption chunk active at timestamp t (in seconds).
- to_event()[source]
Create the CaptionsAnimation event that drives this Captions drawable.
- Return type:
- class handanim.CaptionsAnimation(captions=None, start_time=0.0, duration=None, easing_fun=None, data=None)[source]
Bases:
AnimationEventSingle timeline event that drives a Captions drawable across the narration duration.
- Parameters:
- class handanim.CaptionWord(word, start, end, speaker=None, em=False, color=None)[source]
Bases:
objectNormalized word timing entry for Captions.
- Parameters:
- word: str
- start: float
- end: float
- em: bool = False
- 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:
DrawableA hierarchical transform node with its own pivot and child nodes.
Children attached to a RigNode inherit its rotation (around pivot), scale (around pivot), and translation (offset).
- Parameters:
- add_child(child_or_name, pivot=None, drawables=None, children=None, angle=0.0, offset=(0.0, 0.0), scale_factor=(1.0, 1.0), *args, **kwargs)[source]
- add_slot(slot_or_name, variants=None, default=None, pivot=None, *args, **kwargs)[source]
- has_scheduled_variants()[source]
Return True if this node or any descendant VariantSlot has a non-empty time schedule.
- Return type:
- get_local_transform_params(pose=None)[source]
- draw_with_pose(pose=None, time=None)[source]
Evaluate this node and all descendants under pose via forward kinematics.
- class handanim.VariantSlot(name, variants=None, default=None, pivot=(0.0, 0.0), *args, **kwargs)[source]
Bases:
RigNodeA swappable sprite/shape slot (e.g. eyes or mouth) attached to a parent RigNode.
Inherits all parent transforms while switching its active drawable based on the current Pose.variants[name] or a scheduled time series.
- Parameters:
- set_schedule(entries)[source]
Set a time-sorted schedule of (timestamp, variant_name) switches.
- add_switch(time, variant_name)[source]
Schedule a switch to variant_name at time (in seconds).
- 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.
- 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.
- class handanim.TwoJointLimb(name, upper_node, lower_node, effector_pos, bend_direction=1)[source]
Bases:
objectTwo-bone inverse kinematics chain descriptor (e.g. upper arm + forearm).
- Parameters:
- name
Identifier used in Pose.ik_targets[name].
- Type:
- upper_node
Name of the upper RigNode (e.g. “upper_arm_r”).
- Type:
- lower_node
Name of the lower RigNode (e.g. “forearm_r”), which must be a child of upper_node.
- Type:
- bend_direction
+1 or -1 controlling which way the middle joint bends.
- Type:
- name: str
- upper_node: str
- lower_node: str
- bend_direction: int = 1
- class handanim.CharacterRig(root=None, limbs=None, rest_pose=None, pivot=(0.0, 0.0), *args, **kwargs)[source]
Bases:
DrawableArticulated 2D character rig combining hierarchical
RigNodeobjects,TwoJointLimbIK, andVariantSlotnodes.- Parameters:
- limbs: dict[str, TwoJointLimb]
- add_child(child_or_name, pivot=None, drawables=None, children=None, angle=0.0, offset=(0.0, 0.0), scale_factor=(1.0, 1.0), *args, **kwargs)[source]
Attach a child RigNode directly to self.root.
- add_slot(slot_or_name, variants=None, default=None, pivot=None, *args, **kwargs)[source]
Attach a VariantSlot directly to self.root.
- add_limb(limb)[source]
- Parameters:
limb (TwoJointLimb)
- Return type:
None
- add_two_joint_limb(name, parent=None, root_pivot=(0.0, 0.0), length1=80.0, length2=70.0, bend_direction=1, *, mid_pivot=None, effector_pos=None, effector=None, upper_node=None, lower_node=None, upper_drawables=None, lower_drawables=None, stroke_style=None, sketch_style=None)[source]
Create or register a two-joint IK limb (upper_node -> lower_node) on this rig.
- has_scheduled_variants()[source]
Return True if any VariantSlot in this rig has a non-empty time schedule.
- Return type:
- transform_point_for_node(node_name, point, pose=None)[source]
Transform a rest-space point attached to node_name into world coordinates under pose.
- get_joint_world_pos(node_name, pose=None)[source]
Return the world-space position of node_name’s pivot under pose.
- get_limb_effector_world_pos(limb_name, pose=None)[source]
Return the world-space position of a TwoJointLimb’s end effector under pose.
- resolve_pose(pose=None)[source]
Merge pose with rest_pose and solve any ik_targets into concrete joint angles.
- reach(limb_name, target_pos, base_pose=None)[source]
Return a new Pose with limb_name’s IK angles solved to reach target_pos.
- point_at(scene, target, limb_name=None, start_time=0.0, duration=0.5, hold=1.0, return_duration=0.45, return_to_rest=True, base_pose=None, overlay=False)[source]
Animate limb_name reaching/pointing toward target (a Drawable or (x, y) tuple).
Returns the created PoseAnimation (and registers it on scene if scene is provided).
- sync_to_audio(scene, audio_clip, start_time=0.0, mouth_slot='mouth', open_variant='open', closed_variant='neutral', smile_variant='smile', head_node='head', head_bob_angle=2.0, interval=0.11, overlay=False)[source]
Drive mouth VariantSlot lip-sync and subtle head bobbing from audio_clip.
Reads word timing intervals (and WAV amplitude envelope when available) from audio_clip to schedule mouth switches on mouth_slot, and creates a PoseAnimation spanning the narration duration so draw_with_pose(…, time=t) is evaluated on every frame.
- draw_with_pose(pose=None, time=None)[source]
- class handanim.Pose(angles=<factory>, offsets=<factory>, scales=<factory>, ik_targets=<factory>, variants=<factory>)[source]
Bases:
objectDeclarative snapshot of a CharacterRig configuration.
- Parameters:
- offsets
Mapping of node name to local (dx, dy) translation offset.
- scales
Mapping of node name to local (sx, sy) scale multiplier.
- ik_targets
Mapping of limb name to world-space (x, y) target point.
- 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:
- 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:
DrawableA 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.
- p2n(point)[source]
Map a world-space point (wx, wy) back to the scalar value on the number line.
- 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:
DrawableA 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).
- p2c(wx, wy)[source]
Convert world coordinates (wx, wy) into mathematical coordinates (x, y).
- 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.
- 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.
- 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:
DrawableA hand-sketched curve $y = f(x)$ plotted on an Axes coordinate system.
- Parameters:
- 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:
DrawableA hand-sketched bar chart with category labels, value annotations, and per-bar sub-drawables.
- Parameters:
values (Sequence[float])
labels (Sequence[str] | None)
width (float)
height (float)
bar_colors (Sequence[tuple[float, float, float]] | tuple[float, float, float] | None)
fill_opacity (float)
fill_strategy (str)
bar_width_ratio (float)
show_values (bool)
value_suffix (str)
title (str | None)
font_size (int)
font_name (str | None)
stroke_style (StrokeStyle | None)
sketch_style (SketchStyle | None)
- axes_drawable
The L-shaped baseline and vertical axis drawable.
- Type:
- bars_group
A “series” DrawableGroup of bar_drawables for sequential reveal.
- Type:
- get_bar_top(index)[source]
Return the world-space (x, y) coordinates of the top-center of bar index.
- 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:
DrawableA 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.
- 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:
DrawableA 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:
target (Drawable | BoundingBox | tuple[Any, ...])
opacity (float)
padding (float)
style (str)
passes (int)
stroke_style (StrokeStyle | None)
sketch_style (SketchStyle | None)
- is_emphasis_overlay: bool = True
- 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:
DrawableA hand-drawn curly brace ({) spanning a drawable or two endpoints, with an optional label.
- Parameters:
- label_position
Suggested anchor point for a text/math label outside the tip.
- is_emphasis_overlay: bool = True
- 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:
DrawableA hand-sketched speech or annotation callout bubble with a pointer tail aimed at tail_target.
- Parameters:
text (str)
width (float | None)
height (float | None)
padding (float)
font_size (int)
font_name (str | None)
fill_opacity (float)
stroke_style (StrokeStyle | None)
sketch_style (SketchStyle | None)
- is_emphasis_overlay: bool = True
- 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:
DrawableA bold hand-sketched red ‘X’ or strike-through over a target drawable to debunk a misconception.
- Parameters:
target (Drawable | BoundingBox | tuple[Any, ...])
style (str)
width (float)
padding (float)
stroke_style (StrokeStyle | None)
sketch_style (SketchStyle | None)
- is_emphasis_overlay: bool = True
- class handanim.TimeDrivenAnimation(drawable, start_time=0.0, duration=0.0, easing_fun=None, data=None)[source]
Bases:
AnimationEventAnimation event that delegates per-frame rendering to a TimeDrivenDrawable.
- class handanim.TimeDrivenDrawable(duration=10.0, start_time=0.0, stroke_style=None, sketch_style=None, **kwargs)[source]
Bases:
DrawableBase 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:
duration (float)
start_time (float)
stroke_style (StrokeStyle | None)
sketch_style (SketchStyle | None)
- draw_at_time(t, progress=None)[source]
Render the drawable’s OpsSet at scene timestamp t (in seconds).
- to_event()[source]
Create the TimeDrivenAnimation event that drives this drawable over [start_time, start_time + duration].
- Return type:
TimeDrivenAnimation
- class handanim.CustomTimeDrawable(render_fn, duration=10.0, start_time=0.0, **kwargs)[source]
Bases:
TimeDrivenDrawableWraps 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:
- 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:
TimeDrivenDrawableA 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.
- 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:
TimeDrivenDrawableA hand-sketched linear progress bar for scene.overlay or scene.background.
- Parameters:
- 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:
DrawableA subtle hand-sketched paper background (“grid”, “ruled”, or “dots”) for scene.background.
- Parameters:
- 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:
AnimationEventA 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:
- 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.
- 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:
- 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:
- get_partial_sketch(opsset, progress)[source]
Calculate a partial OpsSet representing the sketching progress of an operation set.
- Parameters:
- Returns:
- A new OpsSet containing the operations up to the specified progress point,
with the last operation potentially being partially completed.
- Return type:
- class handanim.FadeInAnimation(start_time=0.0, duration=0.0, easing_fun=None, data=None, initial_opacity=0.0)[source]
Bases:
AnimationEventA 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:
FadeInAnimationA 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:
AnimationEventA 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:
ZoomInAnimationA 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:
ZoomInAnimationZoom-in animation with an overshoot ‘pop’ easing (ease_out_back).
- 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:
AnimationEventTranslate an OpsSet by a relative (dx, dy) offset over duration seconds.
- handanim.TranslateByAnimation
alias of
MoveBy
- class handanim.TranslateFromAnimation(start_time=0, duration=0, easing_fun=None, data=None)[source]
Bases:
TranslateToAnimationA 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:
AnimationEventA 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:
AnimationEventAnimates 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:
AnimationEventInterpolates 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:
AnimationEventAnimates 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.
- class handanim.MorphAnimation(target_drawable=None, start_time=0.0, duration=1.0, easing_fun=None, points_per_subpath=24, data=None)[source]
Bases:
AnimationEventSmoothly 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)
- 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:
AnimationEventAnimates 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:
rig (CharacterRig)
- Return type:
- get_pose_at_progress(raw_progress)[source]
Compute the blended Pose and scene timestamp at raw_progress in [0, 1].
- class handanim.SceneTransition(start_time=0.0, duration=1.0, easing_fun=<function ease_in_out_cubic>, data=None)[source]
Bases:
AnimationEventBase 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.
- 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].
- 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:
SceneTransitionFolds 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].
- 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:
SceneTransitionCrumples 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].
- class handanim.Show(start_time=0.0, duration=0.0, easing_fun=None, data=None)[source]
Bases:
AnimationEventInstantly 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.
- class handanim.Hide(start_time=0.0, duration=0.0, easing_fun=None, data=None)[source]
Bases:
AnimationEventInstantly hides a drawable at start_time.
- class handanim.Swap(source, target, start_time=0.0, duration=0.0, easing_fun=None, data=None)[source]
Bases:
AnimationEventAtomically 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)
- 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.
- handanim.ease_in_quad(t)[source]
Quadratic ease-in: f(t) = t^2.
- handanim.ease_out_quad(t)[source]
Quadratic ease-out: f(t) = 1 - (1 - t)^2.
- handanim.ease_in_out_quad(t)[source]
Quadratic ease-in-out.
- handanim.ease_in_cubic(t)[source]
Cubic ease-in: f(t) = t^3.
- handanim.ease_out_cubic(t)[source]
Cubic ease-out: f(t) = 1 - (1 - t)^3.
- handanim.ease_in_out_cubic(t)[source]
Cubic ease-in-out: accelerates to midpoint then decelerates smoothly.
- handanim.ease_in_out(t)
Cubic ease-in-out: accelerates to midpoint then decelerates smoothly.
- handanim.ease_in_back(t, overshoot=1.70158)[source]
Back ease-in: pulls back slightly before accelerating forward.
- handanim.ease_out_back(t, overshoot=1.9)[source]
Overshoot ‘pop’ ease-out: overshoots 1.0 slightly then settles back to 1.0.
- handanim.ease_in_out_back(t, overshoot=1.70158)[source]
Symmetric back ease-in-out with slight pull-back and overshoot.
- handanim.ease_out_elastic(t)[source]
Elastic spring ease-out.
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