Skip to main content

Interactive controls

Besides the features on this page, wanim is almost fully compatible with stock manim code. If you want an AI to write a wanim demo, give it https://wanim.org/llms.txt — it covers this page plus the full supported subset, presentation modes and the sharing API.

Drag a value, flip a switch, and watch the picture respond. This page covers how to write, use, and configure such scenes.

Write an interactive scene​

An interactive scene inherits from InteractiveScene and splits its script into two methods:

class Demo(InteractiveScene):
def blueprint(self):
... # build the picture and the controls

def construct(self):
... # the animation, played after the reader presses Next

Try the example below: drag the slider, flip the switch, or type in the number. Then press > at the bottom-right of the canvas to run the animation.

How the two methods work​

  • blueprint() builds the picture and places the controls. It stays live: while the reader is on this page, it runs again on every frame, so the picture follows the reader.
  • construct() runs when the reader presses >. From there the scene is an ordinary manim scene: self.play, self.wait, and add_updater all work. Reactions (below) stop working.

Controls are ordinary mobjects. You can place them, animate them, and read their values with get_value(). For a 3D scene, inherit from InteractiveThreeDScene instead; the 3D section below shows an example.

Reactions: add_reaction​

The connection between a control and the picture is made with add_reaction. A reaction is a small function that changes an object based on the current value of a control:

circle.add_reaction(lambda m: m.set_width(slider.get_value()))

Read it from the inside out:

  • lambda m: ... is a function that takes one argument, which the code calls m. Here m is the object the reaction belongs to, which is circle.
  • m.set_width(...) changes the width of that object.
  • slider.get_value() returns the slider's current value.

wanim calls the function once per frame during the blueprint. The circle's width therefore follows the slider. You do not need to write a loop or an update step.

A few rules:

  • An object can have several reactions. They run in the order you added them, so several controls can drive one object.
  • A reaction can also belong to the whole scene. self.add_reaction(refresh) calls refresh(scene) once per frame, after the object reactions. Use it for updates that touch several objects at once, such as rearranging a group.
  • Reactions run only during the blueprint. In construct(), use add_updater.
  • Reactions run every frame, so keep them cheap. The most common slowdown is creating new Text objects inside a reaction. For a number that changes, create a DecimalNumber once and call set_value(...) on it each frame.

Interactive 3D scenes​

InteractiveThreeDScene is the 3D version. It has the 3D camera of ThreeDScene and the blueprint and construct model above. On an idle blueprint page, the reader can drag empty space to orbit the camera and scroll to zoom. Controls keep working: pointer events go to a control first, and only a drag on the background moves the camera.

Labels, controls, and any HUD text should be added with add_fixed_in_frame_mobjects. Otherwise they are placed in the 3D scene and tilt with the camera. The camera moves only on idle blueprint pages. While self.play(...) runs, orbit and zoom are paused.

Interactive linear transformations​

InteractiveLinearTransformationScene is the live version of manim's LinearTransformationScene. It prebuilds the grey background grid, the transformable foreground grid and the i_hat / j_hat basis vectors, then keeps a 2×2 matrix as state instead of playing one animation.

It deliberately adds no controls or drag handles. You choose how the reader changes the matrix and call set_matrix(...) from your own reaction or on_input listener. Here two DraggablePoints set the two matrix columns:

  • set_matrix([[a, b], [c, d]]) replaces the matrix absolutely and redraws instantly. Call it from a reaction or on_input.
  • apply_matrix(...) / apply_inverse(...) / apply_transposed_matrix(...) / apply_inverse_transpose(...) compose incrementally (B @ M). In blueprint they apply instantly; in construct they animate exactly like the base scene and compose the matrix state when the animation finishes.
  • add_vector(v, animate=False) draws M @ v and keeps it in sync.
  • add_transformable_mobject(...) and add_moving_mobject(...) register other source-space mobjects that should follow the matrix.
  • add_foreground_mobject(...) pins a mobject above everything else and leaves it out of the transformation. Plain additions are not transformed either; use this when the fixed object must also stay on top (titles, formulas, read-outs).
  • get_matrix() reads the current matrix; refresh_transform() redraws after you mutate self.matrix in place.
  • Vectors, the unit square and registered mobjects are source-space objects; the foreground grid shows their image under the current matrix.

Any control works, not just draggable points. For example, use InputDecimalMatrix cells as a matrix editor:

editor = InputDecimalMatrix([[1, 0], [0, 1]],
element_to_mobject_config={"num_decimal_places": 1})
cells = editor.mob_matrix

def apply_editor(control, previous, next_value):
self.set_matrix([
[cells[0][0].get_value(), cells[0][1].get_value()],
[cells[1][0].get_value(), cells[1][1].get_value()],
])

for row in cells:
for cell in row:
cell.on_input(apply_editor)
self.add(editor)

Use construct() for the ordinary animated part of the story, exactly like any other InteractiveScene.

How to use it​

While a blueprint page is idle, you can:

  • Drag a slider's knob along its track.
  • Drag a DraggablePoint (or any other control the scene author added).
  • Click a switch or chip to toggle it.
  • Click a number to type a new value. Press Enter, or click elsewhere, to confirm. Press Escape to cancel. Drag a number up or down to scrub it.
  • Drag on a 3D scene's background to orbit, and scroll to zoom.

To move on, use the buttons in the bottom-right corner of the canvas:

  • > goes to the next page. On a blueprint, this runs its construct().
  • < goes to the previous page.
  • ↻ replays the current page.

Keyboard shortcuts: Space or → for the next page, ← for the previous page, and ↑ to replay. They do not fire while you are typing in a number field.

Controls​

ControlInteractionget_value() returns
Slider(start, end, value_range, init_value)drag along a straight trackfloat
PathSlider(path, value_range, is_closed)drag along any curve or closed loopfloat
DraggablePoint([x, y, 0])drag freely across the planeget_center() → np.array([x, y, 0])
Switch(value)click to togglebool
Chip(label, value)click a tag-like togglebool
InputDecimalNumber(value, num_decimal_places)click to type, drag to scrubfloat
InputInteger(value)click to type, drag to scrub in whole stepsint
InputDecimalMatrix([[...], ...])edit any cell; the matrix re-lays outthe cell's get_value()
InputDecimalTable([[...], ...])edit any cell; grid lines rebuildthe cell's get_value()

Slider and PathSlider​

Slider moves along the straight line from start to end. value_range sets the values at the two ends, and init_value sets the starting value.

slider = Slider(
start=axes.c2p(0, 0),
end=axes.c2p(4, 0),
value_range=(0.5, 3), # the left end is 0.5, the right end is 3
init_value=1,
color=YELLOW,
track_opacity=1, # set to 0 to hide the track
knob_opacity=1, # set to 0 to hide the knob
)

PathSlider works the same way along any VMobject, such as an arc, a polyline, or a VGroup joined into a path. Values follow arc length, and dragging stays on the path. For a closed loop such as a Circle, set is_closed=True. Values then wrap around, and dragging across the seam continues from the other side.

path = Arc(radius=2, start_angle=0, angle=PI)
angle_slider = PathSlider(path, value_range=(0, 180), init_value=90, color=YELLOW)

Hovering over the knob or dragging it enlarges it slightly. Set knob_active_scale to change the amount, or to 1 to turn the effect off.

To use your own shape as the knob, hide the built-in knob and attach the shape:

thumb = Triangle(fill_opacity=1, color=BLUE)
thumb.move_to(slider.knob.get_center())
slider.attach(thumb) # the built-in knob becomes invisible; thumb follows the value

unattach() removes the attached shapes, and attached lists them. Hit testing always uses the track, so the control can still be dragged when the knob is invisible.

Draggable points​

DraggablePoint is a Dot that the reader can drag anywhere on the plane. It takes the same initial point and styling options as Dot. Read the position with the ordinary get_center(), which returns a numpy array:

  • get_center() is exact even with attached mobjects; point.get_center()[0] and point.get_center()[1] read the coordinates.
  • attach(mobject) / unattach(mobject) parent labels or shapes to the point.
  • snap=1 (or snap=[x_step, y_step]) rounds the dragged position to a grid.
  • set_value([x, y, 0]) moves it from code without firing on_input.
  • Like other controls, put it directly on the stage rather than inside a group that later moves or scales.

Switch and Chip​

Switch is a slide toggle. Chip is a tag-like toggle: a rounded box with a label and a trailing ×. Clicking anywhere on either flips its boolean value.

is_green = Switch(True) # the first argument is the starting state
is_green.set_value(False)
is_green.toggle()
square.add_reaction(lambda m: m.set_color(GREEN if is_green.get_value() else RED))

tag = Chip("angle form", value=False, color=PURPLE_C, height=0.45, font_size=20)
label.add_reaction(lambda m: m.set_opacity(1 if tag.get_value() else 0))

Both return a bool from get_value(), accept set_value(...) and toggle(), and support on_input(listener) like the other controls. A selected chip tints its fill, border and label with color; an unselected one uses fill_color and stroke_color.

Chip options:

OptionDefaultMeaning
valueFalseinitial selected state
colorWHITEaccent colour of the label and selected border/fill
height0.52chip height in world units
font_size24label font size
padding0.22horizontal padding around the label
corner_radiusheight * 0.22corner radius
fill_colordark greyfill of an unselected chip
stroke_colormid greyborder of an unselected chip
stroke_width1.5border width

Number inputs​

InputDecimalNumber accepts the same arguments as DecimalNumber, plus:

ArgumentDefaultMeaning
value_rangenoneclosed range (low, high). Typed values outside it are clamped to the range
drag_pixels150how many pixels of vertical drag cover the whole range
drag_spanthe range widthhow much the value changes over drag_pixels
highlight_opacity0.25strength of the hover highlight behind the number

Commas are off by default, so 10000 is shown as 10000, not 10,000.

InputInteger works the same way with no decimal places. Its value is always an integer, and dragging moves in whole steps.

note

num_decimal_places also changes how the value is displayed. With one decimal place, a typed 2.03 is shown as 2.0. Use a fixed-precision input when the displayed text must match exactly what the reader typed.

Matrix and table inputs​

InputDecimalMatrix and InputDecimalTable accept the same arguments as DecimalMatrix and DecimalTable. Every cell is an editable number. When a cell changes, the layout updates and the matrix keeps its centre. Pass options to each cell with element_to_mobject_config, for example {"value_range": (0, 10)}.

A = InputDecimalMatrix([[1, 2], [3, 4]], num_decimal_places=1, h_buff=1.5)
A.to_edge(LEFT)
cells = A.get_entries()

det = DecimalNumber(0, num_decimal_places=2).to_edge(DOWN)
det.add_reaction(lambda m: m.set_value(
cells[0].get_value() * cells[3].get_value()
- cells[1].get_value() * cells[2].get_value()
))
self.add(A, det)

For a table, read one cell with T.get_entries_without_labels([1, 1]).get_value(). If your code changes a cell's value, call relayout() to update the layout.

Multi-step stories​

A scene with one blueprint() and one construct() is a single page. To go through several pages in order, use set_storyboard. It takes a list of [blueprint, construct] pairs, one pair per page. set_script is an alias. Define it in setup():

Each pair is one page, and the > button moves through them in order. In a pair, either half can be None to skip it.

Page breaks inside one method​

In slides mode you can also split a single blueprint() or construct() into pages without adding helper methods. Call self.next_slide() where the page should end:

class Split(InteractiveScene):
def blueprint(self):
self.slider = Slider(
start=[-3, -1, 0], end=[3, -1, 0], value_range=(-3, 3), init_value=0
)
self.add(self.slider)
self.next_slide() # page 1 ends here

self.dot = Dot(radius=0.14, color=YELLOW)
self.dot.add_reaction(
lambda m: m.move_to([self.slider.get_value(), 0.5, 0])
)
self.add(self.dot)

def construct(self):
self.play(Create(Circle()))
self.next_slide() # page 2 ends here
self.play(Create(Square()))

The code before the call is one page and the code after it is the next page. The player pauses at every call; > resumes the same method, so objects and Python state built before the break are still there (the scene is not rebuilt). next_slide() works in both halves and can be called several times. In the other presentation modes it does nothing, so the same scene still runs as one page outside slides mode.

This is equivalent to splitting the method into two helpers and scheduling them with set_storyboard, but it keeps one method and one live scene. < and ↻ treat each segment as its own page: they rebuild the scene, fast-forward the earlier segments, and then play the target segment from its beginning.

Presentation modes​

Pacing belongs to the embedding page, not to the Python file; the old wanim_config helper has been removed. Pass mode to runPythonOnCanvas, or set the mode attribute on <wanim-scene>:

modeBehavior
normal (default)Only blueprint pages pause; each construct() plays through and the presentation moves on.
slidesEvery blueprint and construct ends on a pause, so each is a page of its own.
two-viewLoop the animation; double-click the canvas (or press the pointer icon) to take over the live blueprint.
animationLoop the animation only, without navigation controls (for GIF export).
runPythonOnCanvas(code, canvas, { mode: "two-view" });
<wanim-scene mode="two-view">...</wanim-scene>

The playground and Studio expose the first three as Default / Two-view / Slides tabs next to the stage: switching one restarts the current scene in that pacing, and share links keep it (?mode=…).

Several Scene classes in one file still play in order as one presentation. Helper classes that are not scenes are ignored.

Slides mode​

In slides mode, every blueprint and every construct ends on a pause, so each one is a page of its own. A call to self.next_slide() adds further page breaks inside a method (see Page breaks inside one method). < returns to the previous page and restores the control values the reader had set on that blueprint. ↻ replays a blueprint from a clean state, and replays a construct's animation.

Two-view mode​

Two-view is "watch first, then take over". The player starts in the animation state and loops it. In the default shape it runs the blueprint silently with the controls' starting values, then plays construct(), and repeats. Nothing is interactive while this loop runs.

Double-click the canvas, or click the pointer button in the bottom-right corner, to switch to the interaction state. There the blueprint is live: drag controls, then press Space / → / > to play its construct(). < goes back a page and ↻ replays the current page. Double-click again (when the scene has an animation half) to return to the animation loop.

The scene's shape decides how the two halves relate:

  • blueprint() + construct() (default): the animation runs the blueprint silently, then the construct; the interaction state shows the blueprint and plays the construct on demand.
  • SEPARATE = True on the class: the animation loops construct() only, and the interaction state shows blueprint() only.
  • self.clear_stage() at the end of blueprint(): the construct starts on an empty canvas while references such as self.slider still work. The animation clears the stage immediately; the interaction state waits until the reader presses >, so the controls stay visible while they are used.
  • Only construct(): a pure looping animation with no interaction button. Only blueprint(): a pure interaction page navigated with < and >.
class Compare(InteractiveScene):
SEPARATE = True

def blueprint(self):
... # the interactive page

def construct(self):
... # the looping animation

# Or keep the default pairing and call self.clear_stage() at the end of
# blueprint() when the construct should start from an empty canvas.

For embedded exercises, self.post_message("passed", True) sends an event to the page (the JS onMessage callback, or the component's wanim-message event), so the host does not need to poll the scene.