Skip to main content

Examples

Interactive examples showing what you can build with manim-web. Each example includes a live animation and source code.

Integrated Player​

A full-featured playback controller with play/pause, segment navigation, timeline scrubbing, speed control, fullscreen, and export. Use Space to play/pause, ←/→ for segments, Shift+←/→ to scrub, and F for fullscreen.

Source Code
import {
Player,
Circle,
Square,
Triangle,
Create,
Transform,
FadeIn,
FadeOut,
Indicate,
Rotate,
BLACK,
BLUE,
RED,
GREEN,
YELLOW,
} from 'manim-web';

const player = new Player(document.getElementById('container'), {
width: 800,
height: 450,
backgroundColor: BLACK,
});

player.sequence(async (scene) => {
// Create a blue circle
const circle = new Circle({ radius: 1.5, color: BLUE });
await scene.play(new Create(circle));

await scene.wait(0.5);

// Transform to red square
const square = new Square({ sideLength: 3, color: RED });
await scene.play(new Transform(circle, square));

// Indicate
await scene.play(new Indicate(circle));

// Transform to green triangle
const triangle = new Triangle({ color: GREEN });
triangle.scale(2);
await scene.play(new Transform(circle, triangle));

// Rotate 180°
await scene.play(new Rotate(circle, { angle: Math.PI }));

// Fade out
await scene.play(new FadeOut(circle));

// Bring in a yellow circle
const circle2 = new Circle({ radius: 1, color: YELLOW });
await scene.play(new FadeIn(circle2));

await scene.wait(1);
});

Learn More: Player · Circle · Square · Triangle · Create · Transform · Indicate · Rotate


Creates the Manim Community Edition logo using a large blackboard-bold M, a circle, square, and triangle in signature colors, all composed into a VGroup.

Source Code
import {
Circle,
LEFT,
MathTexImage,
ORIGIN,
RIGHT,
Scene,
Square,
Triangle,
UP,
VGroup,
addVec,
scaleVec,
} from 'manim-web';

const scene = new Scene(document.getElementById('container'), {
width: 800,
height: 450,
backgroundColor: '#ece6e2',
});

const logoGreen = '#87c2a5';
const logoBlue = '#525893';
const logoRed = '#e07a5f';
const logoBlack = '#343434';
const dsM = new MathTexImage({ latex: '\\mathbb{M}', fillColor: logoBlack });
await dsM.waitForRender();
dsM.scale(7);
dsM.shift(addVec(scaleVec(2.25, LEFT), scaleVec(1.5, UP)));
const circle = new Circle({ color: logoGreen, fillOpacity: 1 }).shift(LEFT);
const square = new Square({ color: logoBlue, fillOpacity: 1 }).shift(UP);
const triangle = new Triangle({ color: logoRed, fillOpacity: 1 }).shift(RIGHT);
const logo = new VGroup(triangle, square, circle, dsM);
logo.moveTo(ORIGIN);
scene.add(logo);

Learn More: MathTex · Circle · Square · Triangle · VGroup


Brace Annotation​

Shows how to annotate lines with curly braces and labels. Creates a diagonal line between two dots, then adds horizontal and perpendicular braces with text and LaTeX labels.

Source Code
import { Brace, Dot, Line, ORANGE, Scene } from 'manim-web';

const scene = new Scene(document.getElementById('container'), {
width: 800,
height: 450,
backgroundColor: '#000000',
});

const dot = new Dot({ point: [-2, -1, 0] });
const dot2 = new Dot({ point: [2, 1, 0] });
const line = new Line({ start: dot.getCenter(), end: dot2.getCenter() }).setColor(ORANGE);
const b1 = new Brace(line);
const b1text = b1.getText('Horizontal distance');
const b2 = new Brace(line, {
direction: line
.copy()
.rotate(Math.PI / 2)
.getUnitVector(),
});
const b2text = b2.getTex('x-x_1', { fontSize: 48 });
scene.add(line, dot, dot2, b1, b2, b1text, b2text);

Learn More: Brace · Dot · Line


Vector Arrow​

Displays a vector arrow on a coordinate plane with labeled origin and tip points. Demonstrates combining NumberPlane, Arrow, Dot, and Text for basic vector visualization.

Source Code
import { Arrow, DOWN, Dot, NumberPlane, ORIGIN, RIGHT, Scene, Text, YELLOW } from 'manim-web';

const scene = new Scene(document.getElementById('container'), {
width: 800,
height: 450,
backgroundColor: '#000000',
});

const dot = new Dot({ point: ORIGIN, radius: 0.12, color: YELLOW });
const arrow = new Arrow({ start: ORIGIN, end: [2, 2, 0] });
const numberplane = new NumberPlane();
const originText = new Text({ text: '(0, 0)' }).nextTo(dot, DOWN);
const tipText = new Text({ text: '(2, 2)' }).nextTo(arrow.getEnd(), RIGHT);
scene.add(numberplane, dot, arrow, originText, tipText);

Learn More: Arrow · NumberPlane · Dot · Text


Boolean Operations​

Demonstrates the four boolean set operations (union, intersection, difference, exclusion) applied to overlapping ellipses. Each result is scaled down and labeled with animated transitions.

Source Code
import {
BLUE,
BooleanResult,
Difference,
DOWN,
Ellipse,
Exclusion,
FadeIn,
GREEN,
Group,
Intersection,
LEFT,
ORANGE,
PINK,
RED,
RIGHT,
Scene,
Text,
TransformFromCopy,
Underline,
UP,
Union,
WHITE,
YELLOW,
scaleVec,
} from 'manim-web';

const scene = new Scene(document.getElementById('container'), {
width: 800,
height: 450,
backgroundColor: '#000000',
});

const ellipse1 = new Ellipse({
width: 4.0,
height: 5.0,
fillOpacity: 0.5,
color: BLUE,
strokeWidth: 2,
}).moveTo(LEFT);
const ellipse2 = ellipse1.copy().setColor(RED).moveTo(RIGHT);
// Large italic underlined title matching Python Manim reference
const bool_ops_text = new Text({
text: 'Boolean Operation',
fontFamily: 'serif',
fontSize: 48,
}).nextTo(ellipse1, UP);
const ellipse_group = new Group(bool_ops_text, ellipse1, ellipse2).moveTo(scaleVec(3, LEFT));
// Create underline AFTER group is positioned so it uses the text's final position
const underline = new Underline(bool_ops_text, { color: WHITE, strokeWidth: 2, buff: 0.05 });
ellipse_group.add(underline);
await scene.play(new FadeIn(ellipse_group));

// Layout matching Python Manim reference:
// Intersection
// Difference Union
// Exclusion
// Intersection, Union, Exclusion are vertically aligned on the right.
// Difference is offset to the left at the same row as Union.
// Scales matching Python Manim reference:
// Intersection: scale(0.25), move_to(RIGHT*5 + UP*2.5)
// Union: scale(0.3), next_to(i, DOWN, buff=text.height*3)
// Exclusion: scale(0.3), next_to(u, DOWN, buff=text.height*3.5)
// Difference: scale(0.3), next_to(u, LEFT, buff=text.height*3.5)
const rightX = 5;

// Each result is placed in its slot first, then grows out of the two source
// ellipses: copies of both circles peel off and morph into the result. This
// shows every result originating from the circles instead of popping in.
const emerge = async (result: BooleanResult, label: Text): Promise<void> => {
await scene.play(
new TransformFromCopy(ellipse1, result),
new TransformFromCopy(ellipse2, result),
);
label.nextTo(result, UP);
await scene.play(new FadeIn(label));
};

const i = new Intersection(ellipse1, ellipse2, { color: GREEN, fillOpacity: 0.5 });
i.scale(0.25).setStrokeWidth(1).moveTo([rightX, 2.5, 0]);
await emerge(i, new Text({ text: 'Intersection', fontSize: 23 }));

const union_text = new Text({ text: 'Union', fontSize: 23 });
const u = new Union(ellipse1, ellipse2, { color: ORANGE, fillOpacity: 0.5 });
u.scale(0.3)
.setStrokeWidth(1.2)
.nextTo(i, DOWN, union_text.getHeight() * 3);
await emerge(u, union_text);

const exclusion_text = new Text({ text: 'Exclusion', fontSize: 23 });
const e = new Exclusion(ellipse1, ellipse2, { color: YELLOW, fillOpacity: 0.5 });
e.scale(0.3)
.setStrokeWidth(1.2)
.nextTo(u, DOWN, exclusion_text.getHeight() * 3.5);
await emerge(e, exclusion_text);

const difference_text = new Text({ text: 'Difference', fontSize: 23 });
const d = new Difference(ellipse1, ellipse2, { color: PINK, fillOpacity: 0.5 });
d.scale(0.3)
.setStrokeWidth(1.2)
.nextTo(u, LEFT, difference_text.getHeight() * 3.5);
await emerge(d, difference_text);

Learn More: Union · Intersection · Difference · Exclusion · Ellipse · FadeIn · MoveToTarget


Mathtex Svg​

Demonstrates vector-based LaTeX rendering with MathTex. Shows Create (stroke-draw reveal), DrawBorderThenFill, FadeIn, and multi-part expressions with per-part coloring. MathTex produces real VMobject paths that support path-based animations.

Source Code
import {
Scene,
MathTex,
Create,
DrawBorderThenFill,
FadeIn,
FadeOut,
Transform,
Scale,
Shift,
Rotate,
BLACK,
WHITE,
RED,
BLUE,
GREEN,
TEAL,
GOLD,
} from 'manim-web';

const scene = new Scene(document.getElementById('container'), {
width: 800,
height: 450,
backgroundColor: BLACK,
});

// Pre-create all equations
const equation1 = new MathTex({
latex: '\\int_0^\\infty e^{-x^2} dx = \\frac{\\sqrt{\\pi}}{2}',
color: WHITE,
});
const equation2 = new MathTex({
latex: 'e^{i\\pi} + 1 = 0',
color: GOLD,
});
const multiPart = new MathTex({
latex: ['E', '=', 'mc^2'],
color: WHITE,
});
const equation3 = new MathTex({
latex: '\\sum_{k=1}^{n} k = \\frac{n(n+1)}{2}',
color: GREEN,
});
const matrix = new MathTex({
latex: 'A = \\begin{pmatrix} a_{11} & a_{12} \\\\ a_{21} & a_{22} \\end{pmatrix}',
color: WHITE,
});

// Equations for transform demos
const pythagoras = new MathTex({
latex: 'a^2 + b^2 = c^2',
color: WHITE,
});
const pythagorasExpanded = new MathTex({
latex: 'c = \\sqrt{a^2 + b^2}',
color: TEAL,
});
const scalingEq = new MathTex({
latex: '\\nabla \\cdot \\mathbf{E} = \\frac{\\rho}{\\epsilon_0}',
color: GREEN,
});
const shiftingEq = new MathTex({
latex: '\\lim_{x \\to \\infty} f(x)',
color: RED,
});
const rotatingEq = new MathTex({
latex: '\\frac{\\partial f}{\\partial x}',
color: BLUE,
});
const textBefore = new MathTex({
latex: 'x = 1',
color: WHITE,
});
const textAfter = new MathTex({
latex: 'x = 42',
color: GOLD,
});

// Render all SVGs in parallel
await Promise.all([
equation1.waitForRender(),
equation2.waitForRender(),
multiPart.waitForRender(),
equation3.waitForRender(),
matrix.waitForRender(),
pythagoras.waitForRender(),
pythagorasExpanded.waitForRender(),
scalingEq.waitForRender(),
shiftingEq.waitForRender(),
rotatingEq.waitForRender(),
textBefore.waitForRender(),
textAfter.waitForRender(),
]);

// 1. Create animation - stroke-draw reveal (the main feature)
await scene.play(new Create(equation1, { duration: 3 }));
await scene.wait(1);
await scene.play(new FadeOut(equation1));

// 2. DrawBorderThenFill animation
await scene.play(new DrawBorderThenFill(equation2, { duration: 2 }));
await scene.wait(1);
await scene.play(new FadeOut(equation2));

// 3. Multi-part with per-part coloring
multiPart.getPart(0).setColor(RED);
multiPart.getPart(1).setColor(WHITE);
multiPart.getPart(2).setColor(BLUE);

await scene.play(new FadeIn(multiPart));
await scene.wait(2);
await scene.play(new FadeOut(multiPart));

// 4. Another Create with a summation
await scene.play(new Create(equation3, { duration: 2 }));
await scene.wait(2);
await scene.play(new FadeOut(equation3));

// 5. 2x2 matrix with subscript indices
await scene.play(new Create(matrix, { duration: 2 }));
await scene.wait(2);
await scene.play(new FadeOut(matrix));

// 6. Transform one equation into another
await scene.play(new FadeIn(pythagoras));
await scene.wait(1);
await scene.play(new Transform(pythagoras, pythagorasExpanded, { duration: 2 }));
await scene.wait(1);
// After Transform, source (pythagoras) visually becomes target, target is removed
await scene.play(new FadeOut(pythagoras));

// 7. Scale animation
await scene.play(new FadeIn(scalingEq));
await scene.wait(0.5);
await scene.play(new Scale(scalingEq, { scaleFactor: 2, duration: 1.5 }));
await scene.wait(0.5);
await scene.play(new Scale(scalingEq, { scaleFactor: 0.5, duration: 1 }));
await scene.wait(0.5);
await scene.play(new FadeOut(scalingEq));

// 8. Shift animation
await scene.play(new FadeIn(shiftingEq));
await scene.wait(0.5);
await scene.play(new Shift(shiftingEq, { direction: [3, 0, 0], duration: 1 }));
await scene.wait(0.5);
await scene.play(new Shift(shiftingEq, { direction: [-6, 0, 0], duration: 1 }));
await scene.wait(0.5);
await scene.play(new Shift(shiftingEq, { direction: [3, 2, 0], duration: 1 }));
await scene.wait(0.5);
await scene.play(new FadeOut(shiftingEq));

// 9. Rotate animation
await scene.play(new FadeIn(rotatingEq));
await scene.wait(0.5);
await scene.play(new Rotate(rotatingEq, { angle: Math.PI * 2, duration: 2 }));
await scene.wait(0.5);
await scene.play(new FadeOut(rotatingEq));

// 10. ReplacementTransform - change text
await scene.play(new FadeIn(textBefore));
await scene.wait(1);
await scene.play(new Transform(textBefore, textAfter, { duration: 1.5 }));
await scene.wait(1);
// After Transform, textBefore is morphed to look like textAfter
await scene.play(new FadeOut(textBefore));

Learn More: MathTex · Create · DrawBorderThenFill · FadeIn · FadeOut


Point Moving On Shapes​

Grows a circle from its center, transforms a dot to a new position, moves it along the circle path with MoveAlongPath, and rotates it around an external point with Rotating.

Source Code
import {
BLUE,
Circle,
Dot,
GrowFromCenter,
Line,
MoveAlongPath,
RIGHT,
Rotating,
Scene,
Transform,
linear,
BLACK,
} from 'manim-web';

const scene = new Scene(document.getElementById('container'), {
width: 800,
height: 450,
backgroundColor: BLACK,
});

const circle = new Circle({ radius: 1, color: BLUE });
const dot = new Dot();
const dot2 = dot.copy().shift(RIGHT);
scene.add(dot);

const line = new Line({ start: [3, 0, 0], end: [5, 0, 0] });
scene.add(line);

await scene.play(new GrowFromCenter(circle));
await scene.play(new Transform(dot, dot2));
await scene.play(new MoveAlongPath(dot, { path: circle, duration: 2, rateFunc: linear }));
await scene.play(new Rotating(dot, { aboutPoint: [2, 0, 0], duration: 1.5 }));
await scene.wait();

Learn More: Circle · Dot · GrowFromCenter · Transform · MoveAlongPath · Rotating


Moving Around​

Demonstrates the MoveToTarget pattern for animating a square through a sequence of transformations: shifting, changing fill color, scaling, and rotating.

Source Code
import {
Scene,
Square,
Shift,
MoveToTarget,
Scale,
Rotate,
BLUE,
ORANGE,
LEFT,
BLACK,
} from 'manim-web';

const scene = new Scene(document.getElementById('container'), {
width: 800,
height: 450,
backgroundColor: BLACK,
});

const square = new Square({ color: BLUE, fillOpacity: 1 });

await scene.play(new Shift(square, { direction: LEFT }));

square.generateTarget();
square.targetCopy.setFill(ORANGE);
await scene.play(new MoveToTarget(square));

await scene.play(new Scale(square, { scaleFactor: 0.3 }));

await scene.play(new Rotate(square, { angle: 0.4 }));

Learn More: Square · MoveToTarget


Moving Angle​

Creates two lines forming an angle with a LaTeX theta label, then animates the angle changing using a ValueTracker. The angle arc and label update reactively via addUpdater.

Source Code
import {
Angle,
FadeToColor,
LEFT,
Line,
MathTexImage,
RED,
RIGHT,
SMALL_BUFF,
Scene,
ValueTracker,
BLACK,
WHITE,
} from 'manim-web';

const scene = new Scene(document.getElementById('container'), {
width: 800,
height: 450,
backgroundColor: BLACK,
});

const rotation_center = LEFT;

const theta_tracker = new ValueTracker(110);
const line1 = new Line({ start: LEFT, end: RIGHT });
const line_moving = new Line({ start: LEFT, end: RIGHT });
const line_ref = line_moving.copy();
line_moving.rotate(theta_tracker.getValue() * (Math.PI / 180), { aboutPoint: rotation_center });
const a = new Angle({ line1: line1, line2: line_moving }, { radius: 0.5, otherAngle: false });
const tex = new MathTexImage({ latex: '\\theta', color: WHITE });
await tex.waitForRender();
tex.moveTo(
new Angle(
{ line1: line1, line2: line_moving },
{ radius: 0.5 + 3 * SMALL_BUFF, otherAngle: false },
).pointFromProportion(0.5),
);

scene.add(line1, line_moving, a, tex);
await scene.wait(1);

line_moving.addUpdater((x) => {
x.become(line_ref.copy());
x.rotate(theta_tracker.getValue() * (Math.PI / 180), { aboutPoint: rotation_center });
});

a.addUpdater((x) =>
x.become(new Angle({ line1: line1, line2: line_moving }, { radius: 0.5, otherAngle: false })),
);
tex.addUpdater((x) =>
x.moveTo(
new Angle(
{ line1: line1, line2: line_moving },
{ radius: 0.5 + 3 * SMALL_BUFF, otherAngle: false },
).pointFromProportion(0.5),
),
);

await scene.play(theta_tracker.animateTo(40));
await scene.play(theta_tracker.animateTo(theta_tracker.getValue() + 140));
await scene.play(new FadeToColor(tex, { color: RED, duration: 0.5 }));
await scene.play(theta_tracker.animateTo(350));

await scene.wait(1);

Learn More: Angle · Line · MathTex · ValueTracker · FadeToColor


Moving Dots​

Creates two dots connected by a line, then animates them independently using ValueTrackers. The connecting line updates reactively via addUpdater and the become() method.

Source Code
import { Scene, Dot, VGroup, Line, ValueTracker, BLUE, GREEN, RED, RIGHT } from 'manim-web';

const scene = new Scene(document.getElementById('container'), {
width: 800,
height: 450,
backgroundColor: '#000000',
});

const d1 = new Dot({ color: BLUE });
const d2 = new Dot({ color: GREEN });
new VGroup(d1, d2).arrange(RIGHT, 1);
const l1 = new Line({ start: d1.getCenter(), end: d2.getCenter() }).setColor(RED);
const x = new ValueTracker(0);
const y = new ValueTracker(0);
d1.addUpdater((z) => z.setX(x.getValue()));
d2.addUpdater((z) => z.setY(y.getValue()));
l1.addUpdater((z) => z.become(new Line({ start: d1.getCenter(), end: d2.getCenter() })));
scene.add(d1, d2, l1);
await scene.play(x.animateTo(5));
await scene.play(y.animateTo(4));
await scene.wait();

Learn More: Dot · Line · VGroup · ValueTracker


Moving Group To Destination​

Arranges a group of dots in a row, then shifts the entire group so a specific dot aligns with a target position. Shows vector math with subVec for computing shift direction.

Source Code
import {
Scene,
VGroup,
Dot,
Shift,
LEFT,
ORIGIN,
RIGHT,
RED,
YELLOW,
BLACK,
scaleVec,
subVec,
} from 'manim-web';

const scene = new Scene(document.getElementById('container'), {
width: 800,
height: 450,
backgroundColor: BLACK,
});

const group = new VGroup(
new Dot({ point: LEFT }),
new Dot({ point: ORIGIN }),
new Dot({ point: RIGHT, color: RED }),
new Dot({ point: scaleVec(2, RIGHT) }),
).scale(1.4);

const dest = new Dot({ point: [4, 3, 0], color: YELLOW });

scene.add(group, dest);

await scene.play(
new Shift(group, {
direction: subVec(dest.getCenter(), group.get(2).getCenter()),
}),
);
await scene.wait(0.5);

Learn More: VGroup · Dot · Shift


Moving Frame Box​

Renders a multi-part LaTeX equation (the product rule), then highlights individual terms with a SurroundingRectangle that animates between terms using ReplacementTransform.

Source Code
import {
Create,
MathTexImage,
ReplacementTransform,
Scene,
SurroundingRectangle,
Write,
} from 'manim-web';
const scene = new Scene(document.getElementById('container'), {
width: 800,
height: 450,
backgroundColor: '#000000',
});

const text = new MathTexImage({
latex: ['\\frac{d}{dx}f(x)g(x)=', 'f(x)\\frac{d}{dx}g(x)', '+', 'g(x)\\frac{d}{dx}f(x)'],
});
await text.waitForRender();
await scene.play(new Write(text));
const framebox1 = new SurroundingRectangle(text.getPart(1), { buff: 0.1 });
const framebox2 = new SurroundingRectangle(text.getPart(3), { buff: 0.1 });
await scene.play(new Create(framebox1));
await scene.wait();
await scene.play(new ReplacementTransform(framebox1, framebox2));
await scene.wait();

Learn More: MathTex · SurroundingRectangle · Create · ReplacementTransform


Rotation Updater​

Shows a reference line alongside a rotating line driven by a time-based updater function. The updater is swapped mid-animation to reverse the rotation direction.

Source Code
import { Scene, Line, ORIGIN, LEFT, WHITE, YELLOW } from 'manim-web';

const scene = new Scene(document.getElementById('container'), {
width: 800,
height: 450,
backgroundColor: '#000000',
});

const updaterForth = (mobj, dt) => {
mobj.rotateAboutOrigin(dt);
};
const updaterBack = (mobj, dt) => {
mobj.rotateAboutOrigin(-dt);
};
const lineReference = new Line({ start: ORIGIN, end: LEFT }).setColor(WHITE);
const lineMoving = new Line({ start: ORIGIN, end: LEFT }).setColor(YELLOW);
lineMoving.addUpdater(updaterForth);
scene.add(lineReference, lineMoving);
await scene.wait(2);
lineMoving.removeUpdater(updaterForth);
lineMoving.addUpdater(updaterBack);
await scene.wait(2);
lineMoving.removeUpdater(updaterBack);
await scene.wait(0.5);

Learn More: Line


Point With Trace​

Creates a dot that leaves a visible trail as it moves. Uses a VMobject with addUpdater to continuously extend the path, then rotates and shifts the dot to draw a pattern.

Source Code
import { Scene, VMobject, Dot, Rotating, Shift, UP, LEFT, RIGHT, BLACK } from 'manim-web';

const scene = new Scene(document.getElementById('container'), {
width: 800,
height: 450,
backgroundColor: BLACK,
});

const path = new VMobject();
path.fillOpacity = 0;
const dot = new Dot();
path.setPointsAsCorners([dot.getCenter(), dot.getCenter()]);

const updatePath = (pathMob) => {
const previousPath = pathMob.copy();
previousPath.addPointsAsCorners([dot.getCenter()]);
pathMob.become(previousPath);
};
path.addUpdater(updatePath);

scene.add(path, dot);

await scene.play(new Rotating(dot, { angle: Math.PI, aboutPoint: RIGHT, duration: 2 }));
await scene.wait();
await scene.play(new Shift(dot, { direction: UP }));
await scene.play(new Shift(dot, { direction: LEFT }));
await scene.wait();

Learn More: VMobject · Dot · Rotating · Shift


Sine Curve Unit Circle​

Animates a dot orbiting a unit circle while tracing the corresponding sine curve. Uses addUpdater for continuous motion, with connecting lines from origin-to-dot and dot-to-curve updating each frame.

Source Code
import {
Scene,
Circle,
Dot,
Line,
VGroup,
MathTexImage,
BLACK,
BLUE,
RED,
YELLOW,
YELLOW_A,
YELLOW_D,
DOWN,
} from 'manim-web';

const TAU = 2 * Math.PI;

const scene = new Scene(document.getElementById('container'), {
width: 800,
height: 450,
backgroundColor: BLACK,
});

// --- Axes ---
const xAxis = new Line({ start: [-6, 0, 0], end: [6, 0, 0] });
const yAxis = new Line({ start: [-4, -2, 0], end: [-4, 2, 0] });
scene.add(xAxis, yAxis);

// --- X labels ---
const xLabels = [
new MathTexImage({ latex: '\\pi' }),
new MathTexImage({ latex: '2\\pi' }),
new MathTexImage({ latex: '3\\pi' }),
new MathTexImage({ latex: '4\\pi' }),
];
for (let i = 0; i < xLabels.length; i++) {
xLabels[i].nextTo([-1 + 2 * i, 0, 0], DOWN, 0.4);
scene.add(xLabels[i]);
}

const originPoint = [-4, 0, 0];
const curveStart = [-3, 0, 0];

// --- Circle ---
const circle = new Circle({ radius: 1, center: originPoint, color: RED });
scene.add(circle);

// --- Dot orbiting the circle ---
let tOffset = 0;
const rate = 0.25;

const dot = new Dot({
radius: 0.08,
color: YELLOW,
point: circle.pointAtAngle(0),
});

const goAroundCircle = (_mob, dt) => {
tOffset += dt * rate;
dot.moveTo(circle.pointAtAngle((tOffset % 1) * TAU));
};
dot.addUpdater(goAroundCircle);

// --- Line from origin to dot (always_redraw equivalent) ---
const originToCircleLine = new Line({
start: originPoint,
end: dot.getPoint(),
color: BLUE,
});
originToCircleLine.addUpdater(() => {
originToCircleLine.setStart(originPoint);
originToCircleLine.setEnd(dot.getPoint());
});

// --- Line from dot to curve (always_redraw equivalent) ---
const dotToCurveLine = new Line({
start: dot.getPoint(),
end: dot.getPoint(),
color: YELLOW_A,
strokeWidth: 2,
});
dotToCurveLine.addUpdater(() => {
const x = curveStart[0] + tOffset * 4;
const y = dot.getPoint()[1];
dotToCurveLine.setStart(dot.getPoint());
dotToCurveLine.setEnd([x, y, 0]);
});

// --- Growing sine curve ---
const curve = new VGroup();
curve.add(new Line({ start: curveStart, end: curveStart, color: YELLOW_D }));
let lastEnd = [...curveStart];

curve.addUpdater(() => {
const x = curveStart[0] + tOffset * 4;
const y = dot.getPoint()[1];
const newLine = new Line({
start: lastEnd,
end: [x, y, 0],
color: YELLOW_D,
});
curve.add(newLine);
lastEnd = [x, y, 0];
});

// Add in order: dot first so tOffset/position updates before lines read it
scene.add(dot, originToCircleLine, dotToCurveLine, curve);

await scene.wait(8.5);

dot.removeUpdater(goAroundCircle);

Learn More: Circle · Dot · Line · VGroup · MathTex


Apply Matrix Arrows​

Shows how ApplyMatrix works on Arrows and a NumberPlane. A shear transformation is applied to multiple arrows, and their tips are automatically reconstructed so they remain properly shaped.

Source Code
import { Arrow, NumberPlane, Scene, Text, YELLOW, GREEN_C, RED_C, applyMatrix } from 'manim-web';

const scene = new Scene(document.getElementById('container'), {
width: 800,
height: 450,
backgroundColor: '#000000',
});

const plane = new NumberPlane();
scene.add(plane);

const arrow1 = new Arrow({ start: [-2, -1, 0], end: [2, 1, 0], color: YELLOW });
const arrow2 = new Arrow({ start: [0, -2, 0], end: [0, 2, 0], color: GREEN_C });
const arrow3 = new Arrow({ start: [-1, 1, 0], end: [1, -1, 0], color: RED_C });

scene.add(arrow1, arrow2, arrow3);

const label = new Text({ text: 'Before shear', fontSize: 48, color: '#ffffff' });
label.moveTo([0, 3.2, 0]);
scene.add(label);

await scene.wait(1);

// Shear matrix: x' = x + 0.5*y, y' = y
const shearMatrix = [
[1, 0.5, 0],
[0, 1, 0],
[0, 0, 1],
];

// Apply the shear to the plane and arrows simultaneously
await scene.play(
applyMatrix(plane, shearMatrix, { duration: 2 }),
applyMatrix(arrow1, shearMatrix, { duration: 2 }),
applyMatrix(arrow2, shearMatrix, { duration: 2 }),
applyMatrix(arrow3, shearMatrix, { duration: 2 }),
);

// Update label
scene.remove(label);
const label2 = new Text({
text: 'After shear — tips reconstructed',
fontSize: 48,
color: '#ffffff',
});
label2.moveTo([0, 3.2, 0]);
scene.add(label2);

await scene.wait(2);

Learn More: Arrow · NumberPlane · ApplyMatrix


Apply Matrix Method​

Demonstrates the applyMatrix method on Mobject for instant matrix transformations. Shows shearing, rotation, and scaling with aboutEdge — all applied directly without animation.

Source Code
import { Scene, Square, applyMatrix, BLUE } from 'manim-web';

const scene = new Scene(document.getElementById('container'), {
width: 800,
height: 450,
backgroundColor: '#000000',
});

const square = new Square({ sideLength: 2, color: BLUE, fillOpacity: 0.5 });
scene.add(square);
await scene.wait(1);

// Animate the shear transformation
await scene.play(
applyMatrix(
square,
[
[1, 0.5, 0],
[0, 1, 0],
[0, 0, 1],
],
{ duration: 2 },
),
);

await scene.wait(2);

Learn More: Square · Circle · FadeIn


Rate Functions Comparison​

Example demonstrating Rate Functions Comparison.

Source Code
import {
Scene,
Dot,
Text,
Line,
Shift,
AnimationGroup,
RIGHT,
LEFT,
BLACK,
BLUE,
RED,
GREEN,
YELLOW,
PURPLE,
ORANGE,
WHITE,
smooth,
runningStart,
thereAndBackWithPause,
lingering,
exponentialDecay,
slowInto,
scaleVec,
} from 'manim-web';

const scene = new Scene(document.getElementById('container'), {
width: 800,
height: 450,
backgroundColor: BLACK,
});

// Rate functions to compare, each with a label and color
const rateFunctions: Array<{
name: string;
rateFunc: (t: number) => number;
color: string;
}> = [
{ name: 'smooth', rateFunc: smooth, color: BLUE },
{ name: 'runningStart', rateFunc: runningStart(-0.2), color: RED },
{ name: 'thereAndBackWithPause', rateFunc: thereAndBackWithPause(), color: GREEN },
{ name: 'lingering', rateFunc: lingering, color: YELLOW },
{ name: 'exponentialDecay', rateFunc: exponentialDecay(), color: PURPLE },
{ name: 'slowInto', rateFunc: slowInto, color: ORANGE },
];

const ROW_COUNT = rateFunctions.length;
const TOP_Y = 2.4;
const ROW_SPACING = 0.85;
const START_X = -1.5;
const SHIFT_DISTANCE = 5.5;

const dots: Dot[] = [];
const shiftDirection = scaleVec(SHIFT_DISTANCE, RIGHT) as [number, number, number];

for (let i = 0; i < ROW_COUNT; i++) {
const y = TOP_Y - i * ROW_SPACING;
const { name, color } = rateFunctions[i];

// Track line (faint guide)
const trackLine = new Line({
start: [START_X, y, 0],
end: [START_X + SHIFT_DISTANCE, y, 0],
color: '#333333',
strokeWidth: 1,
});

// Label on the left, right-edge aligned just before track start
const label = new Text({
text: name,
fontSize: 28,
color: WHITE,
});
label.nextTo(trackLine, LEFT, 0.2);

// Dot at the start position
const dot = new Dot({
point: [START_X, y, 0],
radius: 0.1,
color,
});

scene.add(label, trackLine, dot);
dots.push(dot);
}

// Build simultaneous shift animations with different rate functions
const animations = dots.map(
(dot, i) =>
new Shift(dot, {
direction: shiftDirection,
duration: 3,
rateFunc: rateFunctions[i].rateFunc,
}),
);

await scene.play(new AnimationGroup(animations));

Easing Functions Showcase​

Compares eight easing functions side by side. Colored dots shift right simultaneously using different rate functions — smooth, sine, back, elastic, bounce, circ, smoothstep, and exponential — to visualize how each one affects animation timing.

Source Code
import {
Scene,
Dot,
Text,
Line,
Shift,
AnimationGroup,
RIGHT,
LEFT,
BLACK,
BLUE,
RED,
GREEN,
YELLOW,
PURPLE,
ORANGE,
WHITE,
smooth,
easeInOutSine,
easeInOutBack,
easeOutElastic,
easeOutBounce,
easeInOutCirc,
smoothstep,
easeInOutExpo,
scaleVec,
} from 'manim-web';

const scene = new Scene(document.getElementById('container'), {
width: 800,
height: 450,
backgroundColor: BLACK,
});

// Rate functions to compare, each with a label and color
const rateFunctions: Array<{
name: string;
rateFunc: (t: number) => number;
color: string;
}> = [
{ name: 'smooth', rateFunc: smooth, color: BLUE },
{ name: 'easeInOutSine', rateFunc: easeInOutSine, color: RED },
{ name: 'easeInOutBack', rateFunc: easeInOutBack, color: GREEN },
{ name: 'easeOutElastic', rateFunc: easeOutElastic, color: YELLOW },
{ name: 'easeOutBounce', rateFunc: easeOutBounce, color: PURPLE },
{ name: 'easeInOutCirc', rateFunc: easeInOutCirc, color: ORANGE },
{ name: 'smoothstep', rateFunc: smoothstep, color: '#ff69b4' },
{ name: 'easeInOutExpo', rateFunc: easeInOutExpo, color: '#00ced1' },
];

const ROW_COUNT = rateFunctions.length;
const TOP_Y = 3.0;
const ROW_SPACING = 0.75;
const START_X = -1.2;
const SHIFT_DISTANCE = 5.5;

const dots: Dot[] = [];
const shiftDirection = scaleVec(SHIFT_DISTANCE, RIGHT) as [number, number, number];

for (let i = 0; i < ROW_COUNT; i++) {
const y = TOP_Y - i * ROW_SPACING;
const { name, color } = rateFunctions[i];

// Track line (faint guide)
const trackLine = new Line({
start: [START_X, y, 0],
end: [START_X + SHIFT_DISTANCE, y, 0],
color: '#333333',
strokeWidth: 1,
});

// Label on the left, right-edge aligned just before track start
const label = new Text({
text: name,
fontSize: 26,
color: WHITE,
});
label.nextTo(trackLine, LEFT, 0.2);

// Dot at the start position
const dot = new Dot({
point: [START_X, y, 0],
radius: 0.1,
color,
});

scene.add(label, trackLine, dot);
dots.push(dot);
}

// Build simultaneous shift animations with different rate functions
const animations = dots.map(
(dot, i) =>
new Shift(dot, {
direction: shiftDirection,
duration: 3,
rateFunc: rateFunctions[i].rateFunc,
}),
);

await scene.play(new AnimationGroup(animations));

Learn More: Shift · AnimationGroup


Sin Cos Plot​

Plots sine and cosine functions on labeled coordinate axes with color-coded graphs. Adds a vertical reference line at x=2π with a label. Demonstrates Axes.plot() and getGraphLabel().

Source Code
import {
Axes,
BLUE,
GREEN,
Line,
RED,
Scene,
UP,
UR,
VGroup,
WHITE,
YELLOW,
scaleVec,
BLACK,
} from 'manim-web';

const scene = new Scene(document.getElementById('container'), {
width: 854,
height: 480,
backgroundColor: BLACK,
});

const axes = new Axes({
xRange: [-10, 10.3, 1],
yRange: [-1.5, 1.5, 1],
xLength: 10,
axisConfig: { color: GREEN },
xAxisConfig: {
numbersToInclude: [-10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10],
numbersWithElongatedTicks: [-10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10],
},
tips: false,
});
const axesLabels = axes.getAxisLabels();
const sinGraph = axes.plot((x) => Math.sin(x), { color: BLUE });
const cosGraph = axes.plot((x) => Math.cos(x), { color: RED });

const sinLabel = axes.getGraphLabel(sinGraph, '\\sin(x)', {
xVal: -10,
direction: scaleVec(0.5, UP),
});
const cosLabel = axes.getGraphLabel(cosGraph, { label: '\\cos(x)' });

const vertLine = axes.getVerticalLine(axes.i2gp(2 * Math.PI, cosGraph), {
color: YELLOW,
lineFunc: Line,
});
const lineLabel = axes.getGraphLabel(cosGraph, 'x=2\\pi', {
xVal: 2 * Math.PI,
direction: UR,
color: WHITE,
});

const plot = new VGroup(axes, sinGraph, cosGraph, vertLine);
const labels = new VGroup(axesLabels, sinLabel, cosLabel, lineLabel);
scene.add(plot, labels);

Learn More: Axes · Line · VGroup


Arg Min​

Plots a quadratic function on coordinate axes and animates a dot that slides along the curve to find the minimum value. Uses a ValueTracker to drive the animation and addUpdater for reactive positioning.

Source Code
import { Scene, Axes, Dot, MAROON, ValueTracker, linspace, BLACK } from 'manim-web';

const scene = new Scene(document.getElementById('container'), {
width: 800,
height: 450,
backgroundColor: BLACK,
});

const ax = new Axes({
xRange: [0, 10],
yRange: [0, 100, 10],
axisConfig: { includeTip: false },
});
const labels = ax.getAxisLabels({ xLabel: 'x', yLabel: 'f(x)' });

const t = new ValueTracker(0);

const func = (x) => {
return 2 * (x - 5) ** 2;
};
const graph = ax.plot(func, { color: MAROON });

const initialPoint = [ax.coordsToPoint(t.getValue(), func(t.getValue()))];
const dot = new Dot({ point: initialPoint });

dot.addUpdater((x) => x.moveTo(ax.coordsToPoint(t.getValue(), func(t.getValue()))));
const xSpace = linspace(...ax.xRange.slice(0, 2), 200);
const minimumIndex = xSpace.reduce((mi, _, i, a) => (func(a[i]) < func(a[mi]) ? i : mi), 0);

scene.add(ax, labels, graph, dot);
await scene.play(t.animateTo(xSpace[minimumIndex]));
await scene.wait();

Learn More: Axes · Dot · ValueTracker


Graph Area Plot​

Draws two curves on coordinate axes with vertical reference lines, a shaded area between the curves, and Riemann sum rectangles. Demonstrates the Axes area and Riemann integration visualization methods.

Source Code
import { Axes, BLUE, BLUE_C, GRAY, GREEN_B, Scene, YELLOW, BLACK } from 'manim-web';

const scene = new Scene(document.getElementById('container'), {
width: 854,
height: 480,
backgroundColor: BLACK,
});

const ax = new Axes({
xRange: [0, 5],
yRange: [0, 6],
xAxisConfig: { numbersToInclude: [2, 3] },
tips: false,
});
const labels = ax.getAxisLabels();

const curve1 = ax.plot((x) => 4 * x - Math.pow(x, 2), { xRange: [0, 4], color: BLUE_C });
const curve2 = ax.plot((x) => 0.8 * Math.pow(x, 2) - 3 * x + 4, {
xRange: [0, 4],
color: GREEN_B,
});

const line1 = ax.getVerticalLine(ax.inputToGraphPoint(2, curve1), { color: YELLOW });
const line2 = ax.getVerticalLine(ax.i2gp(3, curve1), { color: YELLOW });

const riemannArea = ax.getRiemannRectangles(curve1, {
xRange: [0.3, 0.6],
dx: 0.03,
color: BLUE,
fillOpacity: 0.5,
});
const area = ax.getArea(curve2, [2, 3], { boundedGraph: curve1, color: GRAY, opacity: 0.5 });

scene.add(ax, labels, curve1, curve2, line1, line2, riemannArea, area);

Learn More: Axes


Polygon On Axes​

Draws a dynamic rectangle under a hyperbola curve on coordinate axes. Uses a ValueTracker and always_redraw pattern to animate the rectangle width while keeping it constrained to the curve.

Source Code
import {
Axes,
BLUE,
Create,
Dot,
Polygon,
Scene,
ValueTracker,
YELLOW_B,
YELLOW_D,
BLACK,
} from 'manim-web';

const scene = new Scene(document.getElementById('container'), {
width: 854,
height: 480,
backgroundColor: BLACK,
});

const ax = new Axes({
xRange: [0, 10],
yRange: [0, 10],
xLength: 6,
yLength: 6,
tips: false,
});

const t = new ValueTracker(5);
const k = 25;

const graph = ax.plot((x) => k / x, { color: YELLOW_D, xRange: [k / 10, 10.0], numSamples: 750 });

function makeRectangle() {
const corners = getRectangleCorners([0, 0], [t.getValue(), k / t.getValue()]);
const vertices = corners.map(([x, y]) => ax.c2p(x, y));
const p = new Polygon({ vertices, strokeWidth: 1, color: YELLOW_B, fillOpacity: 0.5 });
p.fillColor = BLUE;
return p;
}

const polygon = makeRectangle();
polygon.addUpdater(() => {
polygon.become(makeRectangle());
});

const dot = new Dot();
dot.addUpdater(() => dot.moveTo(ax.c2p(t.getValue(), k / t.getValue())));

scene.add(ax, graph);
await scene.play(new Create(polygon));
scene.add(dot);
await scene.play(t.animateTo(10));
await scene.play(t.animateTo(k / 10));
await scene.play(t.animateTo(5));

function getRectangleCorners(bottomLeft, topRight) {
return [
[topRight[0], topRight[1]],
[bottomLeft[0], topRight[1]],
[bottomLeft[0], bottomLeft[1]],
[topRight[0], bottomLeft[1]],
];
}

Learn More: Axes · Polygon · ValueTracker


Heat Diagram Plot​

Creates a line graph showing temperature change over time using plotLineGraph. Demonstrates the Axes line graph plotting and axis label methods.

Source Code
import { Scene, Axes, Tex, BLACK } from 'manim-web';

const scene = new Scene(document.getElementById('container'), {
width: 800,
height: 450,
backgroundColor: BLACK,
});

const ax = new Axes({
xRange: [0, 40, 5],
yRange: [-8, 32, 5],
xLength: 9,
yLength: 6,
xAxisConfig: { numbersToInclude: [0, 5, 10, 15, 20, 25, 30, 35] },
yAxisConfig: { numbersToInclude: [-5, 0, 5, 10, 15, 20, 25, 30] },
tips: false,
});

// Create Tex labels and wait for rendering
const xLabel = new Tex({ latex: '$\\Delta Q$', fontSize: 32 });
const yLabel = new Tex({ latex: 'T[$^\\circ C$]', fontSize: 32 });
await xLabel.waitForRender();
await yLabel.waitForRender();

const labels = ax.getAxisLabels({ xLabel, yLabel });

const xVals = [0, 8, 38, 39];
const yVals = [20, 0, 0, -5];
const graph = ax.plotLineGraph({ xValues: xVals, yValues: yVals });

scene.add(ax, labels, graph);

Learn More: Axes · Tex


Following Graph Camera​

Animates a camera that follows a dot moving along a sine curve. Zooms in, tracks with an updater, then restores to the original view. Demonstrates camera frame manipulation with saveState, generateTarget, and MoveToTarget.

Source Code
import {
Axes,
BLUE,
Dot,
MoveAlongPath,
MoveToTarget,
ORANGE,
Restore,
Scene,
linear,
} from 'manim-web';

const scene = new Scene(document.getElementById('container'), {
width: 800,
height: 450,
backgroundColor: '#000000',
});

// Save camera frame state
scene.camera.frame.saveState();

// Create the axes and the curve
const ax = new Axes({ xRange: [-1, 10], yRange: [-1, 10] });
const graph = ax.plot((x) => Math.sin(x), { color: BLUE, xRange: [0, 3 * Math.PI] });

// Create dots based on the graph
const movingDot = new Dot({ point: ax.i2gp(graph.tMin, graph), color: ORANGE });
const dot1 = new Dot({ point: ax.i2gp(graph.tMin, graph) });
const dot2 = new Dot({ point: ax.i2gp(graph.tMax, graph) });

scene.add(ax, graph, dot1, dot2, movingDot);

// Zoom camera to 0.5x and center on moving dot
scene.camera.frame.generateTarget();
scene.camera.frame.targetCopy.scale(0.5);
scene.camera.frame.targetCopy.moveTo(movingDot.getCenter());
await scene.play(new MoveToTarget(scene.camera.frame));

// Add updater so camera follows the moving dot
const updateCurve = (mob) => {
mob.moveTo(movingDot.getCenter());
};
scene.camera.frame.addUpdater(updateCurve);

// Animate dot moving along the graph path
await scene.play(new MoveAlongPath(movingDot, { path: graph, rateFunc: linear }));

// Remove updater and restore camera to original state
scene.camera.frame.removeUpdater(updateCurve);
await scene.play(new Restore(scene.camera.frame));

Learn More: Axes · Dot · MoveAlongPath · MoveToTarget · Restore


Moving Zoomed Scene Around​

Demonstrates ZoomedScene with a camera frame that magnifies part of a grayscale image. Shows the zoomed display popping out, non-uniform scaling, shifting, and the reverse pop-out animation.

Source Code
import {
BackgroundRectangle,
BLACK,
Create,
Dot,
DOWN,
FadeIn,
FadeOut,
ImageMobject,
MED_SMALL_BUFF,
PURPLE,
RED,
Scale,
ScaleInPlace,
Shift,
smooth,
Text,
UL,
Uncreate,
UP,
UpdateFromFunc,
ZoomedScene,
scaleVec,
} from 'manim-web';

const scene = new ZoomedScene(document.getElementById('container'), {
width: 800,
height: 450,
backgroundColor: BLACK,
zoomFactor: 0.3,
displayWidth: 6,
displayHeight: 1,
cameraFrameStrokeWidth: 3,
displayFrameStrokeWidth: 3,
displayFrameColor: RED,
});

// Grayscale image matching Python: np.uint8([[0, 100, 30, 200], [255, 0, 5, 33]])
const image = new ImageMobject({
pixelData: [
[0, 100, 30, 200],
[255, 0, 5, 33],
],
height: 7,
});

const dot = new Dot().shift(scaleVec(2, UL));

const frameText = new Text({ text: 'Frame', color: PURPLE, fontSize: 67 });
const zoomedCameraText = new Text({ text: 'Zoomed camera', color: RED, fontSize: 67 });

scene.add(image, dot);

const zoomedCamera = scene.zoomedCamera;
const zoomedDisplay = scene.zoomedDisplay;
const frame = zoomedCamera.frame;
const zoomedDisplayFrame = zoomedDisplay.displayFrame;

frame.moveTo(dot);
frame.setColor(PURPLE);
zoomedDisplayFrame.setColor(RED);
zoomedDisplay.shift(DOWN);

const zdRect = new BackgroundRectangle(zoomedDisplay, {
fillOpacity: 0,
buff: MED_SMALL_BUFF,
});
scene.addForegroundMobject(zdRect);

const unfoldCamera = new UpdateFromFunc(zdRect, (rect) => {
rect.replace(zoomedDisplay);
});

frameText.nextTo(frame, DOWN);

await scene.play(new Create(frame), new FadeIn(frameText, { shift: UP }));
scene.activateZooming();

// Pop-out animation: display pops from frame position to its shifted position
await scene.play(scene.getZoomedDisplayPopOutAnimation(), unfoldCamera);

zoomedCameraText.nextTo(zoomedDisplay, DOWN);
await scene.play(new FadeIn(zoomedCameraText, { shift: UP }));

// Scale frame and display non-uniformly
await scene.play(
new Scale(frame, { scaleFactor: [0.5, 1.5, 0] }),
new Scale(zoomedDisplay, { scaleFactor: [0.5, 1.5, 0] }),
new FadeOut(zoomedCameraText),
new FadeOut(frameText),
);
await scene.wait();

await scene.play(new ScaleInPlace(zoomedDisplay, { scaleFactor: 2 }));
await scene.wait();

await scene.play(new Shift(frame, { direction: scaleVec(2.5, DOWN) }));
await scene.wait();

// Reverse pop-out: move display back to frame
await scene.play(
scene.getZoomedDisplayPopOutAnimation({ rateFunc: (t: number) => smooth(1 - t) }),
unfoldCamera,
);
await scene.play(new Uncreate(zoomedDisplayFrame), new FadeOut(frame));
await scene.wait();

Learn More: ZoomedScene · ImageMobject · BackgroundRectangle · Create · FadeIn · Scale · Shift


Fixed In Frame Mobject Test​

Demonstrates how to pin 2D text to the screen while the 3D camera is rotated, using addFixedInFrameMobjects. The text stays in the upper-left corner as a HUD overlay on top of ThreeDAxes.

Source Code
import { Text, ThreeDAxes, ThreeDScene, UL } from 'manim-web';

const scene = new ThreeDScene(document.getElementById('container'), {
width: 800,
height: 450,
backgroundColor: '#000000',
phi: 75 * (Math.PI / 180),
theta: -45 * (Math.PI / 180),
distance: 20,
fov: 30,
orbitControlsUp: 'z',
});

const axes = new ThreeDAxes({
xRange: [-6, 6, 1],
yRange: [-5, 5, 1],
zRange: [-4, 4, 1],
axisColor: '#ffffff',
tipLength: 0.3,
tipRadius: 0.12,
shaftRadius: 0.008,
});
const text3d = new Text({ text: 'This is a 3D text' });
scene.addFixedInFrameMobjects(text3d);
text3d.toCorner(UL);
scene.add(axes);
await scene.wait(999999);

Learn More: ThreeDScene · ThreeDAxes · Text


Fixed Orientation Mobjects​

Demonstrates how to keep labels readable in a 3D scene using addFixedOrientationMobjects. Unlike fixed-in-frame (HUD), these labels stay at their 3D world position but always face the camera as it orbits.

Source Code
import { GOLD, Text, ThreeDAxes, ThreeDScene } from 'manim-web';

const scene = new ThreeDScene(document.getElementById('container'), {
width: 800,
height: 450,
backgroundColor: '#000000',
phi: 75 * (Math.PI / 180),
theta: -45 * (Math.PI / 180),
distance: 20,
fov: 30,
orbitControlsUp: 'z',
});

const axes = new ThreeDAxes({
xRange: [-6, 6, 1],
yRange: [-5, 5, 1],
zRange: [-4, 4, 1],
axisColor: '#ffffff',
tipLength: 0.3,
tipRadius: 0.12,
shaftRadius: 0.008,
});

// Create a label that sits in 3D space but always faces the camera.
// Small XY offset + GOLD tint so the text reads against the white axis lines
// without floating away from the origin it labels.
const label = new Text({ text: 'Origin', fontSize: 32, color: GOLD });
label.moveTo([0.4, 0.4, 0.3]);

const xLabel = new Text({ text: 'X', fontSize: 32, color: GOLD });
xLabel.moveTo([6.8, 0, 0.4]);

scene.add(axes, label, xLabel);

// Make the labels always face the camera regardless of orbit angle
scene.addFixedOrientationMobjects(label, xLabel);

// Rotate the camera so the billboard effect is visible
scene.beginAmbientCameraRotation(0.3);
await scene.wait(999999);

Learn More: ThreeDScene · ThreeDAxes · Text


Three D Light Source Position​

Shows a parametric sphere with checkerboard colors (RED_D, RED_E) on ThreeDAxes with custom point light positioning. Demonstrates Surface3D checkerboardColors and the Lighting system.

Source Code
import { ThreeDAxes, ThreeDScene, Surface3D, RED_D, RED_E } from 'manim-web';

const scene = new ThreeDScene(document.getElementById('container'), {
width: 800,
height: 450,
backgroundColor: '#000000',
phi: 75 * (Math.PI / 180),
theta: 30 * (Math.PI / 180),
distance: 20,
fov: 30,
orbitControlsUp: 'z',
});

const axes = new ThreeDAxes({
xRange: [-5, 5, 1],
yRange: [-5, 5, 1],
zRange: [-5, 5, 1],
axisColor: '#ffffff',
tipLength: 0.2,
tipRadius: 0.08,
shaftRadius: 0.01,
});

// Checkerboard sphere matching Python Manim's Surface(..., checkerboard_colors=[RED_D, RED_E])
const sphere = new Surface3D({
func: (u: number, v: number) => [
1.5 * Math.cos(u) * Math.cos(v),
1.5 * Math.cos(u) * Math.sin(v),
1.5 * Math.sin(u),
],
uRange: [-Math.PI / 2, Math.PI / 2],
vRange: [0, 2 * Math.PI],
uResolution: 15,
vResolution: 32,
checkerboardColors: [RED_D, RED_E],
});

// Light from above to match Python Manim's default top-lit appearance
scene.lighting.removeAll();
scene.lighting.addAmbient({ intensity: 0.3 });
scene.lighting.addPoint({ position: [0, 5, 0], intensity: 2.5, decay: 0 });

scene.add(axes);
scene.add(sphere);

await scene.wait(999999);

Learn More: ThreeDScene · ThreeDAxes · Surface3D · Lighting


Three D Surface Plot​

Renders a 3D Gaussian surface plot on ThreeDAxes with checkerboard coloring (ORANGE, BLUE). The parametric surface maps (u,v) to a bell-shaped Gaussian peak, scaled by 2 and displayed with semi-transparent faces.

Source Code
import { ThreeDAxes, ThreeDScene, Surface3D, ORANGE, BLUE } from 'manim-web';

const scene = new ThreeDScene(document.getElementById('container'), {
width: 800,
height: 450,
backgroundColor: '#000000',
phi: 75 * (Math.PI / 180),
theta: -30 * (Math.PI / 180),
distance: 20,
fov: 30,
orbitControlsUp: 'z',
});

const sigma = 0.4;
const mu = [0.0, 0.0];

// Gaussian surface: Z-up Manim convention — height is along z.
const gaussSurface = new Surface3D({
func: (u: number, v: number) => {
const x = u;
const y = v;
const dx = x - mu[0];
const dy = y - mu[1];
const d = Math.sqrt(dx * dx + dy * dy);
const z = Math.exp(-(d * d) / (2.0 * sigma * sigma));
return [x, y, z];
},
uRange: [-2, 2],
vRange: [-2, 2],
uResolution: 24,
vResolution: 24,
checkerboardColors: [ORANGE, BLUE],
opacity: 0.85,
});

// Scale by 2 about origin (matches Python: gauss_plane.scale(2, about_point=ORIGIN)).
// Without an explicit aboutPoint, scale() pivots about the surface's geometric
// center (z≈0.5), which would push the flat base below the z=0 plane.
gaussSurface.scale(2, { aboutPoint: [0, 0, 0] });

const axes = new ThreeDAxes({
xRange: [-6, 6, 1],
yRange: [-5, 5, 1],
zRange: [-4, 4, 1],
axisColor: '#ffffff',
tipLength: 0.3,
tipRadius: 0.12,
shaftRadius: 0.008,
});

scene.add(axes);
scene.add(gaussSurface);
await scene.wait(999999);

Learn More: ThreeDScene · ThreeDAxes · Surface3D


Three D Camera Rotation​

Demonstrates ambient camera rotation around 3D axes with a circle, then animates the camera back to its original orientation. Shows beginAmbientCameraRotation, stopAmbientCameraRotation, and moveCamera methods.

Source Code
import { Circle, ThreeDAxes, ThreeDScene } from 'manim-web';

const scene = new ThreeDScene(document.getElementById('container'), {
width: 800,
height: 450,
backgroundColor: '#000000',
phi: 75 * (Math.PI / 180),
theta: 30 * (Math.PI / 180),
distance: 20,
fov: 30,
orbitControlsUp: 'z',
});

const axes = new ThreeDAxes({
xRange: [-6, 6, 1],
yRange: [-5, 5, 1],
zRange: [-4, 4, 1],
axisColor: '#ffffff',
tipLength: 0.3,
tipRadius: 0.12,
shaftRadius: 0.008,
});

const circle = new Circle({ radius: 1, color: '#FC6255' });
scene.add(circle, axes);

// Begin ambient camera rotation (theta rotates at 0.1 rad/s)
scene.beginAmbientCameraRotation(0.1);
await scene.wait(3);

// Stop rotation and animate camera back to original orientation
scene.stopAmbientCameraRotation();
await scene.moveCamera({
phi: 75 * (Math.PI / 180),
theta: 30 * (Math.PI / 180),
duration: 1,
});
await scene.wait(1);

// Reset camera orientation for replay
scene.setCameraOrientation(75 * (Math.PI / 180), 30 * (Math.PI / 180));

Learn More: ThreeDScene · ThreeDAxes · Circle


Three D Camera Illusion Rotation​

Demonstrates the 3D illusion camera rotation that wobbles the camera by oscillating phi sinusoidally while rotating theta continuously. Creates a convincing 3D parallax effect around ThreeDAxes with a circle.

Source Code
import { Circle, ThreeDAxes, ThreeDScene } from 'manim-web';

const scene = new ThreeDScene(document.getElementById('container'), {
width: 800,
height: 450,
backgroundColor: '#000000',
phi: 75 * (Math.PI / 180),
theta: 30 * (Math.PI / 180),
distance: 20,
fov: 30,
orbitControlsUp: 'z',
});

const axes = new ThreeDAxes({
xRange: [-6, 6, 1],
yRange: [-5, 5, 1],
zRange: [-4, 4, 1],
axisColor: '#ffffff',
tipLength: 0.3,
tipRadius: 0.12,
shaftRadius: 0.008,
});

const circle = new Circle({ radius: 1, color: '#FC6255' });
scene.add(circle, axes);

// Begin 3D illusion camera rotation (theta rotates at 2 rad/s,
// phi oscillates sinusoidally for a wobbling 3D effect)
scene.begin3DIllusionCameraRotation(2);
await scene.wait(Math.PI / 2);

// Stop illusion rotation
scene.stop3DIllusionCameraRotation();

// Reset camera orientation for replay
scene.setCameraOrientation(75 * (Math.PI / 180), 30 * (Math.PI / 180));

Learn More: ThreeDScene · ThreeDAxes · Circle


Three D Angle​

Displays an Angle arc between two Line3D objects in a 3D scene. The arc is drawn in the plane spanned by the two lines, not restricted to the XY plane. Orbit controls are enabled so you can verify the arc lies in the correct plane.

Source Code
import { Angle, Line3D, ThreeDAxes, ThreeDScene, WHITE, YELLOW, GREEN } from 'manim-web';

const scene = new ThreeDScene(document.getElementById('container'), {
width: 800,
height: 450,
backgroundColor: '#000000',
phi: 70 * (Math.PI / 180),
theta: -45 * (Math.PI / 180),
distance: 20,
fov: 30,
enableOrbitControls: true,
orbitControlsUp: 'z',
});

const axes = new ThreeDAxes({
xRange: [-4, 4, 1],
yRange: [-4, 4, 1],
zRange: [-3, 3, 1],
axisColor: '#ffffff',
tipLength: 0.3,
tipRadius: 0.12,
shaftRadius: 0.008,
});

const origin: [number, number, number] = [0, 0, 0];
const p1: [number, number, number] = [2, 0, 0];
const p2: [number, number, number] = [0, 1.5, 2];

const line1 = new Line3D({ start: origin, end: p1, color: YELLOW });
const line2 = new Line3D({ start: origin, end: p2, color: GREEN });

const angle = new Angle({ points: [p1, origin, p2] }, { radius: 0.8, color: WHITE });

scene.add(axes, line1, line2, angle);
await scene.wait(Infinity);

scene.setCameraOrientation(70 * (Math.PI / 180), -45 * (Math.PI / 180));

if (new URLSearchParams(window.location.search).has('embed')) {
document
.querySelectorAll('.controls, .buttons, h1, #status')
.forEach((el) => ((el as HTMLElement).style.display = 'none'));
document.documentElement.style.cssText =
'margin:0;padding:0;width:100%;height:100%;overflow:hidden;background:#000';
document.body.style.cssText =
'margin:0;padding:0;width:100%;height:100%;overflow:hidden;background:#000;display:flex;justify-content:center;align-items:center';
const cont = document.getElementById('container');
if (cont) {
cont.style.cssText =
'border:none;border-radius:0;width:100vw;height:100vh;display:flex;justify-content:center;align-items:center';
}
const svg = cont && cont.querySelector('svg');
if (svg) {
(svg as HTMLElement).style.width = '100%';
(svg as HTMLElement).style.height = '100%';
svg.setAttribute('preserveAspectRatio', 'xMidYMid meet');
}
if (cont) {
new MutationObserver((_, obs) => {
const s = cont.querySelector('svg');
if (s) {
(s as HTMLElement).style.width = '100%';
(s as HTMLElement).style.height = '100%';
s.setAttribute('preserveAspectRatio', 'xMidYMid meet');
obs.disconnect();
}
}).observe(cont, { childList: true, subtree: true });
}
const playBtn = document.getElementById('playBtn') as HTMLButtonElement;
if (playBtn) {
setTimeout(() => playBtn.click(), 500);
new MutationObserver(() => {
if (!playBtn.disabled) setTimeout(() => playBtn.click(), 2000);
}).observe(playBtn, { attributes: true, attributeFilter: ['disabled'] });
}
}

Learn More: ThreeDScene · ThreeDAxes · Line3D · Angle


Three D Reflex Angle​

Sweeps a Line3D around a reference axis in the XZ plane while an Angle arc tracks it continuously from 0 to 2π. Uses the Angle axis option to pin the rotation plane so the reflex arc grows past π without flipping back across the reference line (fix for issue #262).

Source Code
import {
Angle,
Line3D,
ThreeDAxes,
ThreeDScene,
ValueTracker,
WHITE,
YELLOW,
GREEN,
} from 'manim-web';

// Demo for issue #262: a 3D Angle whose arc grows continuously past π to 2π
// when the rotation plane is pinned via the new `axis` option. Sweeps a
// projection line around the +Y axis in the XZ plane so the arc should
// stay coplanar with the two segments at every frame.

const scene = new ThreeDScene(document.getElementById('container'), {
width: 800,
height: 450,
backgroundColor: '#000000',
phi: 70 * (Math.PI / 180),
theta: -40 * (Math.PI / 180),
distance: 20,
fov: 30,
enableOrbitControls: true,
orbitControlsUp: 'z',
});

const axes = new ThreeDAxes({
xRange: [-3, 3, 1],
yRange: [-3, 3, 1],
zRange: [-3, 3, 1],
axisColor: '#ffffff',
tipLength: 0.25,
tipRadius: 0.1,
shaftRadius: 0.008,
});

const origin: [number, number, number] = [0, 0, 0];
const radius = 2;
const axisVec: [number, number, number] = [0, 1, 0];

const refLine = new Line3D({ start: origin, end: [radius, 0, 0], color: YELLOW });

const theta = new ValueTracker(0);

const sweepEnd = (): [number, number, number] => [
radius * Math.cos(theta.getValue()),
0,
-radius * Math.sin(theta.getValue()),
];

const sweepLine = new Line3D({ start: origin, end: sweepEnd(), color: GREEN });
sweepLine.addUpdater((mob) => {
(mob as Line3D).setEnd(sweepEnd());
});

const angle = new Angle(
{ points: [[radius, 0, 0], origin, sweepEnd()] },
{ radius: 0.9, color: WHITE, axis: axisVec },
);
angle.addUpdater((mob) => {
mob.become(
new Angle(
{ points: [[radius, 0, 0], origin, sweepEnd()] },
{ radius: 0.9, color: WHITE, axis: axisVec },
),
);
});

scene.add(axes, refLine, sweepLine, angle);

// Sweep through the full 2π. Before the fix, the arc mirrors across the
// reference line past π. With `axis` pinned, it keeps growing.
await scene.play(theta.animateTo(2 * Math.PI, { duration: 6 }));
await scene.wait(0.5);

scene.setCameraOrientation(70 * (Math.PI / 180), -40 * (Math.PI / 180));

if (new URLSearchParams(window.location.search).has('embed')) {
document
.querySelectorAll('.controls, .buttons, h1, #status')
.forEach((el) => ((el as HTMLElement).style.display = 'none'));
document.documentElement.style.cssText =
'margin:0;padding:0;width:100%;height:100%;overflow:hidden;background:#000';
document.body.style.cssText =
'margin:0;padding:0;width:100%;height:100%;overflow:hidden;background:#000;display:flex;justify-content:center;align-items:center';
const cont = document.getElementById('container');
if (cont) {
cont.style.cssText =
'border:none;border-radius:0;width:100vw;height:100vh;display:flex;justify-content:center;align-items:center';
}
const playBtn = document.getElementById('playBtn') as HTMLButtonElement;
if (playBtn) {
setTimeout(() => playBtn.click(), 500);
new MutationObserver(() => {
if (!playBtn.disabled) setTimeout(() => playBtn.click(), 2000);
}).observe(playBtn, { attributes: true, attributeFilter: ['disabled'] });
}
}

Learn More: ThreeDScene · ThreeDAxes · Line3D · Angle · ValueTracker


Split Screen Camera​

Renders the same scene through two Camera2D instances side by side via SplitScreenCamera. The left pane is centered on a circle; the right pane zooms in on a square. Each viewport gets its own aspect ratio at render time. Demonstrates Scene.useMultiCamera() for split-screen layouts.

Source Code
import {
BLUE,
Camera2D,
Circle,
Create,
RED,
Scene,
SplitScreenCamera,
Square,
YELLOW,
} from 'manim-web';

const scene = new Scene(document.getElementById('container'), {
width: 800,
height: 450,
backgroundColor: '#1a1a2e',
});

// Two independent Camera2D instances framing the same scene at
// different zoom levels. With `aspectMode: 'contain'` the per-camera
// frameWidth/frameHeight is honoured at render time (the viewport
// letterboxes if it doesn't match), so the zoom intent — wide
// overview on the left, tight zoom on the right — actually shows up
// on screen.
const leftCamera = new Camera2D({
frameWidth: 14,
frameHeight: 8,
position: [-3, 0, 10],
aspectMode: 'contain',
});
const rightCamera = new Camera2D({
frameWidth: 4,
frameHeight: 4,
position: [3, 0, 10],
aspectMode: 'contain',
});

const split = new SplitScreenCamera({
leftCamera,
rightCamera,
split: 'horizontal',
splitRatio: 0.5,
});
const mc = split.getMultiCamera();
// Draw a thin border around each pane so the split is visible even
// when one side renders the scene background edge-to-edge.
mc.setViewportBorder(0, { borderColor: '#888888', borderWidth: 2 });
mc.setViewportBorder(1, { borderColor: '#888888', borderWidth: 2 });
scene.useMultiCamera(mc);

const circle = new Circle({ radius: 1, color: RED, strokeWidth: 4 });
circle.shift([-3, 0, 0]);
const square = new Square({ sideLength: 1.5, color: BLUE, strokeWidth: 4 });
square.shift([3, 0, 0]);
const marker = new Circle({ radius: 0.15, color: YELLOW, strokeWidth: 3 });

scene.add(marker);
await scene.play(new Create(circle));
await scene.play(new Create(square));
await scene.wait(0.8);

scene.useMultiCamera(null);

if (new URLSearchParams(window.location.search).has('embed')) {
document
.querySelectorAll('.controls, .buttons, h1, #status')
.forEach((el) => (el.style.display = 'none'));
document.documentElement.style.cssText =
'margin:0;padding:0;width:100%;height:100%;overflow:hidden;background:#000';
document.body.style.cssText =
'margin:0;padding:0;width:100%;height:100%;overflow:hidden;background:#000;display:flex;justify-content:center;align-items:center';
const cont = document.getElementById('container');
if (cont) {
cont.style.cssText =
'border:none;border-radius:0;width:100vw;height:100vh;display:flex;justify-content:center;align-items:center';
}
const playBtn = document.getElementById('playBtn');
if (playBtn) {
setTimeout(() => playBtn.click(), 500);
new MutationObserver(() => {
if (!playBtn.disabled) setTimeout(() => playBtn.click(), 2000);
}).observe(playBtn, { attributes: true, attributeFilter: ['disabled'] });
}
}

Learn More: Scene · Camera2D · SplitScreenCamera · MultiCamera


Picture In Picture Camera​

Main camera shows the full scene while a small picture-in-picture inset follows an orbiting dot at higher zoom. Uses MultiCamera.setupPictureInPicture() and an updater to keep the inset camera tracking the target.

Source Code
import {
Camera2D,
Circle,
Create,
GREEN,
MultiCamera,
PURPLE,
Scene,
Square,
Triangle,
ValueTracker,
YELLOW,
} from 'manim-web';

const scene = new Scene(document.getElementById('container'), {
width: 800,
height: 450,
backgroundColor: '#1a1a2e',
});

// Main camera: wide overview of the whole scene.
const mainCamera = new Camera2D({ frameWidth: 14, frameHeight: 8, position: [0, 0, 10] });

// PiP camera: zoomed-in inset that follows a moving target. `contain`
// keeps the requested 4×4 frame fully visible inside the PiP square
// viewport instead of letting MultiCamera stretch its width.
const pipCamera = new Camera2D({
frameWidth: 4,
frameHeight: 4,
position: [0, 0, 10],
aspectMode: 'contain',
});

const mc = new MultiCamera();
mc.setupPictureInPicture(mainCamera, pipCamera, 'top-right', 0.3);
// Index 0 is the main viewport, index 1 is the PiP inset (per
// setupPictureInPicture's add order). Highlight the PiP so users can
// see where the inset camera is framing.
mc.setViewportBorder(1, { borderColor: '#ffd54f', borderWidth: 3 });
scene.useMultiCamera(mc);

const square = new Square({ sideLength: 1.5, color: PURPLE, strokeWidth: 4 });
const triangle = new Triangle({ color: GREEN, strokeWidth: 4 });
triangle.shift([-4, 1, 0]);
const orbiter = new Circle({ radius: 0.35, color: YELLOW, strokeWidth: 4 });

// ValueTracker drives the orbiter; the PiP camera follows it via updater.
const t = new ValueTracker(0);
orbiter.addUpdater(() => {
const a = t.getValue();
orbiter.moveTo([3 * Math.cos(a), 2 * Math.sin(a), 0]);
const p = orbiter.getCenter();
pipCamera.position.set(p[0], p[1], 10);
});
scene.add(t, square, triangle, orbiter);

await scene.play(new Create(square));
await scene.play(new Create(triangle));
await scene.play(new Create(orbiter));
await scene.play(t.animateTo(Math.PI * 4, { duration: 4 }));
await scene.wait(0.5);

scene.useMultiCamera(null);

if (new URLSearchParams(window.location.search).has('embed')) {
document
.querySelectorAll('.controls, .buttons, h1, #status')
.forEach((el) => (el.style.display = 'none'));
document.documentElement.style.cssText =
'margin:0;padding:0;width:100%;height:100%;overflow:hidden;background:#000';
document.body.style.cssText =
'margin:0;padding:0;width:100%;height:100%;overflow:hidden;background:#000;display:flex;justify-content:center;align-items:center';
const cont = document.getElementById('container');
if (cont) {
cont.style.cssText =
'border:none;border-radius:0;width:100vw;height:100vh;display:flex;justify-content:center;align-items:center';
}
const playBtn = document.getElementById('playBtn');
if (playBtn) {
setTimeout(() => playBtn.click(), 500);
new MutationObserver(() => {
if (!playBtn.disabled) setTimeout(() => playBtn.click(), 2000);
}).observe(playBtn, { attributes: true, attributeFilter: ['disabled'] });
}
}

Learn More: Scene · Camera2D · MultiCamera · ValueTracker


Quad View Camera​

Four simultaneous viewports of the same scene — one overview plus three close-ups — composed with MultiCamera.setupQuadView(). A ball animates between regions, visible at full detail in whichever quadrant currently frames it.

Source Code
import {
BLUE,
Camera2D,
Circle,
Create,
GREEN,
MultiCamera,
ORANGE,
RED,
Scene,
Square,
Triangle,
ValueTracker,
YELLOW,
} from 'manim-web';

const scene = new Scene(document.getElementById('container'), {
width: 800,
height: 450,
backgroundColor: '#1a1a2e',
});

// Four Camera2D instances framing the same scene at different positions
// and zoom levels — a "control room" layout. setupQuadView() places them
// in viewport order [top-left, top-right, bottom-left, bottom-right] on
// the canvas, so the variable names below describe the on-screen pane,
// not the world region the camera looks at.
// `contain` keeps each pane's requested frame fully visible in its
// quad-cell viewport instead of letting MultiCamera stretch widths.
const overviewPane = new Camera2D({
frameWidth: 14,
frameHeight: 8,
position: [0, 0, 10],
aspectMode: 'contain',
});
const circlePane = new Camera2D({
frameWidth: 4,
frameHeight: 4,
position: [-3, 2, 10],
aspectMode: 'contain',
});
const squarePane = new Camera2D({
frameWidth: 4,
frameHeight: 4,
position: [3, 2, 10],
aspectMode: 'contain',
});
const trianglePane = new Camera2D({
frameWidth: 6,
frameHeight: 4,
position: [0, -2, 10],
aspectMode: 'contain',
});

const mc = new MultiCamera();
mc.setupQuadView([overviewPane, circlePane, squarePane, trianglePane]);
// Highlight every cell so the four-pane grid is obvious. Different
// tints make the close-up panes easy to tell apart at a glance.
mc.setViewportBorder(0, { borderColor: '#888888', borderWidth: 2 });
mc.setViewportBorder(1, { borderColor: '#ef5350', borderWidth: 2 });
mc.setViewportBorder(2, { borderColor: '#42a5f5', borderWidth: 2 });
mc.setViewportBorder(3, { borderColor: '#66bb6a', borderWidth: 2 });
scene.useMultiCamera(mc);

const circle = new Circle({ radius: 0.9, color: RED, strokeWidth: 4 });
circle.shift([-3, 2, 0]);
const square = new Square({ sideLength: 1.4, color: BLUE, strokeWidth: 4 });
square.shift([3, 2, 0]);
const triangle = new Triangle({ color: GREEN, strokeWidth: 4 });
triangle.shift([0, -2, 0]);
const ball = new Circle({ radius: 0.25, color: YELLOW, strokeWidth: 3 });

// Animate a "ball" bouncing between the three regions; each quad-view
// close-up shows the ball passing through its quadrant in detail.
const t = new ValueTracker(0);
ball.addUpdater(() => {
const a = t.getValue();
const path: Array<[number, number]> = [
[-3, 2],
[3, 2],
[0, -2],
[-3, 2],
];
const seg = Math.floor(a) % (path.length - 1);
const f = a - Math.floor(a);
const [x0, y0] = path[seg];
const [x1, y1] = path[seg + 1];
ball.moveTo([x0 + (x1 - x0) * f, y0 + (y1 - y0) * f, 0]);
});
scene.add(t);

// Highlight marker that stays at world origin so the overview pane has
// a visible reference point too.
const marker = new Circle({ radius: 0.12, color: ORANGE, strokeWidth: 2 });
scene.add(marker);

scene.add(circle, square, triangle, ball);
await scene.play(new Create(circle));
await scene.play(new Create(square));
await scene.play(new Create(triangle));
await scene.play(new Create(ball));
await scene.play(t.animateTo(3, { duration: 4 }));
await scene.wait(0.5);

scene.useMultiCamera(null);

if (new URLSearchParams(window.location.search).has('embed')) {
document
.querySelectorAll('.controls, .buttons, h1, #status')
.forEach((el) => (el.style.display = 'none'));
document.documentElement.style.cssText =
'margin:0;padding:0;width:100%;height:100%;overflow:hidden;background:#000';
document.body.style.cssText =
'margin:0;padding:0;width:100%;height:100%;overflow:hidden;background:#000;display:flex;justify-content:center;align-items:center';
const cont = document.getElementById('container');
if (cont) {
cont.style.cssText =
'border:none;border-radius:0;width:100vw;height:100vh;display:flex;justify-content:center;align-items:center';
}
const playBtn = document.getElementById('playBtn');
if (playBtn) {
setTimeout(() => playBtn.click(), 500);
new MutationObserver(() => {
if (!playBtn.disabled) setTimeout(() => playBtn.click(), 2000);
}).observe(playBtn, { attributes: true, attributeFilter: ['disabled'] });
}
}

Learn More: Scene · Camera2D · MultiCamera · ValueTracker


Relativity Frames Camera​

Special relativity in two reference frames. Both panes of a SplitScreenCamera look at the same region, but per-camera mobject filters (leftExcludeMobjects / rightExcludeMobjects) decide which objects each pane renders. Left: the rod at rest while the ship flies past at 0.8c. Right: the ship at rest while the Lorentz-contracted rod flies past.

Source Code
import {
BLUE,
Camera2D,
Circle,
Line,
Rectangle,
Scene,
Shift,
SplitScreenCamera,
Text,
WHITE,
YELLOW,
linear,
} from 'manim-web';

const scene = new Scene(document.getElementById('container'), {
width: 800,
height: 450,
backgroundColor: '#1a1a2e',
});

// Special relativity in two reference frames. Both cameras look at the
// same region of the scene; per-camera mobject filters decide which
// version of each object a pane shows. Left pane: the rod's rest frame,
// the ship flies past at v = 0.8c. Right pane: the ship's rest frame,
// the rod flies past Lorentz-contracted to L / gamma.
const v = 0.8;
const gamma = 1 / Math.sqrt(1 - v * v);
const restLength = 4;

const makeCamera = () =>
new Camera2D({ frameWidth: 8, frameHeight: 9, position: [0, 0, 10], aspectMode: 'contain' });

// Shared by both frames.
const axis = new Line({ start: [-4, 0, 0], end: [4, 0, 0], color: WHITE, strokeWidth: 2 });

// Rod rest frame.
const rodAtRest = new Rectangle({
width: restLength,
height: 0.6,
color: BLUE,
fillOpacity: 0.6,
});
const shipMoving = new Circle({ radius: 0.25, color: YELLOW, fillOpacity: 1 });
shipMoving.shift([-3.5, 1, 0]);
const restLabel = new Text({ text: 'Rod frame', fontSize: 36, color: WHITE });
restLabel.shift([0, 3, 0]);

// Ship rest frame.
const rodMoving = new Rectangle({
width: restLength / gamma,
height: 0.6,
color: BLUE,
fillOpacity: 0.6,
});
rodMoving.shift([3.5, 0, 0]);
const shipAtRest = new Circle({ radius: 0.25, color: YELLOW, fillOpacity: 1 });
shipAtRest.shift([0, 1, 0]);
const shipLabel = new Text({ text: 'Ship frame', fontSize: 36, color: WHITE });
shipLabel.shift([0, 3, 0]);

const split = new SplitScreenCamera({
leftCamera: makeCamera(),
rightCamera: makeCamera(),
leftExcludeMobjects: [rodMoving, shipAtRest, shipLabel],
rightExcludeMobjects: [rodAtRest, shipMoving, restLabel],
});
const mc = split.getMultiCamera();
mc.setViewportBorder(0, { borderColor: '#888888', borderWidth: 2 });
mc.setViewportBorder(1, { borderColor: '#888888', borderWidth: 2 });
scene.useMultiCamera(mc);

scene.add(axis, rodAtRest, shipMoving, restLabel, rodMoving, shipAtRest, shipLabel);
await scene.wait(0.5);
await scene.play(
new Shift(shipMoving, { direction: [7, 0, 0], duration: 3, rateFunc: linear }),
new Shift(rodMoving, { direction: [-7, 0, 0], duration: 3, rateFunc: linear }),
);
await scene.wait(0.8);

scene.useMultiCamera(null);

if (new URLSearchParams(window.location.search).has('embed')) {
document
.querySelectorAll('.controls, .buttons, h1, #status')
.forEach((el) => (el.style.display = 'none'));
document.documentElement.style.cssText =
'margin:0;padding:0;width:100%;height:100%;overflow:hidden;background:#000';
document.body.style.cssText =
'margin:0;padding:0;width:100%;height:100%;overflow:hidden;background:#000;display:flex;justify-content:center;align-items:center';
const cont = document.getElementById('container');
if (cont) {
cont.style.cssText =
'border:none;border-radius:0;width:100vw;height:100vh;display:flex;justify-content:center;align-items:center';
}
const playBtn = document.getElementById('playBtn');
if (playBtn) {
setTimeout(() => playBtn.click(), 500);
new MutationObserver(() => {
if (!playBtn.disabled) setTimeout(() => playBtn.click(), 2000);
}).observe(playBtn, { attributes: true, attributeFilter: ['disabled'] });
}
}

Learn More: Scene · SplitScreenCamera · MultiCamera · Shift


Opening Manim​

A multi-part showcase: writes text and a LaTeX equation, transforms the title, creates a NumberPlane grid, and applies a non-linear sine warp using ApplyPointwiseFunction.

Source Code
import {
Scene,
Create,
FadeIn,
FadeOut,
Transform,
ApplyPointwiseFunction,
Text,
MathTexImage,
NumberPlane,
VGroup,
UP,
DOWN,
UL,
BLACK,
WHITE,
} from 'manim-web';

const FONT_URL = 'https://cdn.jsdelivr.net/npm/katex@0.16.0/dist/fonts/KaTeX_Main-Regular.ttf';

const scene = new Scene(document.getElementById('container'), {
width: 800,
height: 450,
backgroundColor: BLACK,
});
// Part 1: Title and equation (Write title, FadeIn equation from below)
const title = new Text({
text: 'This is some LaTeX',
fontSize: 48,
color: WHITE,
fontUrl: FONT_URL,
});
const basel = new MathTexImage({
latex: '\\sum_{n=1}^\\infty \\frac{1}{n^2} = \\frac{\\pi^2}{6}',
});
await basel.waitForRender?.();

new VGroup(title, basel).arrange(DOWN);
scene.add(title, basel);
await scene.play(new FadeIn(title), new FadeIn(basel, { shift: DOWN }));
await scene.wait(1);

// Part 2: Transform title to UL corner, fade out equation downward
const transformTitle = new Text({
text: 'That was a transform',
fontSize: 48,
color: WHITE,
fontUrl: FONT_URL,
});
await transformTitle.loadGlyphs();
transformTitle.toCorner(UL);
await scene.play(new Transform(title, transformTitle), new FadeOut(basel, { shift: DOWN }));
await scene.wait(1);

// Part 3: Number plane grid with title
const grid = new NumberPlane();
const gridTitle = new Text({
text: 'This is a grid',
fontSize: 72,
color: WHITE,
fontUrl: FONT_URL,
});
await gridTitle.loadGlyphs();
gridTitle.moveTo(transformTitle);

await scene.play(
new FadeOut(title),
new FadeIn(gridTitle, { shift: UP }),
new Create(grid, { duration: 3, lagRatio: 0.1 }),
);
await scene.wait(1);

// Part 4: Non-linear grid transform (sin warp)
const gridTransformTitle = new Text({
text: 'That was a non-linear function\napplied to the grid',
fontSize: 48,
color: WHITE,
fontUrl: FONT_URL,
});
await gridTransformTitle.loadGlyphs();
gridTransformTitle.moveTo(gridTitle, UL);
grid.prepareForNonlinearTransform();
await scene.play(
new ApplyPointwiseFunction(
grid,
(p) => {
return [p[0] + Math.sin(p[1]), p[1] + Math.sin(p[0]), p[2]];
},
{ duration: 3 },
),
);
await scene.wait(1);

// Part 5: Transform grid title to explain what happened
await scene.play(new Transform(gridTitle, gridTransformTitle));
await scene.wait(1);

Learn More: Text · MathTex · NumberPlane · Write · Transform · ApplyPointwiseFunction · Create


Export Animation​

Demonstrates the scene.export() convenience API. Creates a square, transforms it into a circle, then exports the animation as GIF or WebM with a progress callback.

Source Code
import {
Scene,
Circle,
Square,
Create,
Transform,
FadeOut,
Animation,
Timeline,
BLACK,
BLUE,
GREEN,
} from 'manim-web';

const container = document.getElementById('container')!;
const scene = new Scene(document.getElementById('container'), {
width: 800,
height: 450,
backgroundColor: BLACK,
});

const progressContainer = document.getElementById('progressContainer')!;
const progressFill = document.getElementById('progressFill')!;
const progressText = document.getElementById('progressText')!;

function showProgress(progress: number, label: string) {
progressContainer.style.display = 'block';
progressFill.style.width = `${Math.round(progress * 100)}%`;
progressText.textContent = `${label} — ${Math.round(progress * 100)}%`;
}

function hideProgress() {
progressContainer.style.display = 'none';
progressFill.style.width = '0%';
}

function setButtonsDisabled(disabled: boolean) {
document
.querySelectorAll<HTMLButtonElement>('.controls button')
.forEach((btn) => (btn.disabled = disabled));
}

// Build the same three animations Play and Export share.
// Each call returns a fresh set against a freshly populated scene
// — animations are stateful (begin() snapshots opacities), so reusing
// instances across runs would replay against stale state.
function buildAnimations(): Animation[] {
scene.clear();
const square = new Square({ sideLength: 2.5, color: BLUE, fillOpacity: 0.5 });
const circle = new Circle({ radius: 1.25, color: GREEN, fillOpacity: 0.5 });
return [
new Create(square, { duration: 1 }),
new Transform(square, circle, { duration: 1 }),
new FadeOut(square, { duration: 1 }),
];
}

// Wire animations into the scene's timeline sequentially without
// starting playback. We avoid Succession here because it would call
// begin() on every child up front — Transform.begin() would then
// snapshot the fillOpacity that Create.begin() just zeroed, leaving
// the square invisible after the morph. Timeline drives each begin()
// lazily inside _updateAnimationsAtTime as forward-seeking crosses
// each animation's start time, which is what GifExporter does.
function installTimeline(anims: Animation[]): number {
scene.add(anims[0].mobject);
const timeline = new Timeline();
for (const anim of anims) timeline.add(anim, '>');
scene.setTimeline(timeline);
return timeline.getDuration();
}

// Play animation
document.getElementById('playBtn')!.addEventListener('click', async () => {
if (isAnimating) return;
isAnimating = true;
setButtonsDisabled(true);

for (const anim of buildAnimations()) {
await scene.play(anim);
}

isAnimating = false;
setButtonsDisabled(false);
});

// Export GIF
document.getElementById('exportGifBtn')!.addEventListener('click', async () => {
if (isAnimating) return;
isAnimating = true;
setButtonsDisabled(true);

try {
const duration = installTimeline(buildAnimations());
await scene.export('animation.gif', {
fps: 15,
quality: 10,
duration,
onProgress: (p) => showProgress(p, 'Exporting GIF'),
});
} catch (err) {
console.error('GIF export failed:', err);
} finally {
hideProgress();
isAnimating = false;
setButtonsDisabled(false);
}
});

// Export WebM
document.getElementById('exportWebmBtn')!.addEventListener('click', async () => {
if (isAnimating) return;
isAnimating = true;
setButtonsDisabled(true);

try {
const duration = installTimeline(buildAnimations());
await scene.export('animation.webm', {
fps: 30,
duration,
onProgress: (p) => showProgress(p, 'Exporting WebM'),
});
} catch (err) {
console.error('WebM export failed:', err);
} finally {
hideProgress();
isAnimating = false;
setButtonsDisabled(false);
}
});

// Reset
document.getElementById('resetBtn')!.addEventListener('click', () => {
scene.clear();
});

Learn More: Scene · Circle · Square · Create · Transform · FadeOut


Manim 3D Look (Toon Shading)​

The manim look for 3D meshes: flat color bands, a soft highlight and a bright rim outline, applied to a whole scene with applyManimStyle3D. The top row builds up with Create3D (outline first, then body) and GrowAlongPath3D (a tube grows along its curve), including translucent parts with opaque cores. The bottom row shows the cartoon preset on a white page.

Source Code
import {
ThreeDScene,
Sphere,
Cube,
Torus,
Cylinder,
TubeFromPoints,
ParametricSurface,
InstancedMobject,
Group,
LaggedStart,
Create3D,
GrowAlongPath3D,
applyManimStyle3D,
applyToonShading,
BLUE,
BLUE_B,
TEAL,
GOLD,
RED,
GREEN,
PURPLE,
YELLOW,
MAROON,
} from 'manim-web';
import type { Mobject } from 'manim-web';

type Vec3 = [number, number, number];

const CAMERA = {
width: 960,
height: 400,
phi: Math.PI / 2.4,
theta: -Math.PI / 2,
distance: 12,
fov: 40,
enableOrbitControls: true,
};

/** A wavy path for the tube, centred on `c`. */
function wave(c: Vec3): Vec3[] {
const pts: Vec3[] = [];
for (let i = 0; i <= 24; i++) {
const t = i / 24;
pts.push([c[0] - 0.9 + 1.8 * t, c[1] + 0.6 * Math.sin(t * Math.PI * 2), c[2] - 0.8 + 1.6 * t]);
}
return pts;
}

/** The five opaque primitives of one row. */
function primitives(z: number, colors: string[]): Mobject[] {
const cube = new Cube({ sideLength: 1.4, center: [-2.8, 0, z], color: colors[1] });
cube.rotation.set(0.5, 0.6, 0);
const torus = new Torus({ radius: 0.75, tubeRadius: 0.3, center: [0, 0, z], color: colors[2] });
torus.rotation.set(1.1, 0.3, 0);
const cylinder = new Cylinder({
radius: 0.6,
height: 1.6,
center: [2.8, 0, z],
color: colors[3],
});
cylinder.rotation.set(0.35, 0, 0.3);
return [
new Sphere({ radius: 0.85, center: [-5.6, 0, z], color: colors[0] }),
cube,
torus,
cylinder,
new TubeFromPoints({ points: wave([5.6, 0, z]), radius: 0.22, color: colors[4], capped: true }),
];
}

// ── Manim preset, dark background ─────────────────────────────────────

const manimScene = new ThreeDScene(document.getElementById('manim')!, CAMERA);
const opaqueRow = primitives(1.3, [BLUE, TEAL, GOLD, RED, GREEN]);

// A translucent sphere with an opaque core.
const glass = new Sphere({ radius: 0.95, center: [-4.2, 0, -1.6], color: PURPLE, opacity: 0.4 });
const core = new Sphere({ radius: 0.4, center: [-4.2, 0, -1.6], color: YELLOW });

// A translucent cutaway shell (a sphere with a wedge removed) with a cube inside.
const shell = new ParametricSurface({
func: (u: number, v: number): Vec3 => [
0.95 * Math.sin(v) * Math.cos(u),
0.95 * Math.sin(v) * Math.sin(u),
-1.6 + 0.95 * Math.cos(v),
],
uRange: [-Math.PI / 2 + 0.6, (3 * Math.PI) / 2 - 0.6],
vRange: [0.05, Math.PI - 0.05],
uResolution: 48,
vResolution: 24,
color: MAROON,
opacity: 0.45,
});
shell.shift([-1.2, 0, 0]);
const inner = new Cube({ sideLength: 0.6, center: [-1.2, 0, -1.6], color: TEAL });
inner.rotation.set(0.4, 0.7, 0);

// A ring of instanced beads.
const beads = new InstancedMobject({
template: new Sphere({ radius: 0.2, color: BLUE_B }),
color: BLUE_B,
instances: Array.from({ length: 12 }, (_, i) => {
const a = (i / 12) * Math.PI * 2;
return { position: [1.8 + 0.9 * Math.cos(a), 0, -1.6 + 0.9 * Math.sin(a)] as Vec3 };
}),
});

const tube = new TubeFromPoints({
points: Array.from({ length: 40 }, (_, i): Vec3 => {
const t = i / 39;
return [4.2 + 0.9 * Math.cos(t * 5), 0.9 * Math.sin(t * 5), -2.5 + 1.8 * t];
}),
radius: 0.14,
color: YELLOW,
capped: true,
});

const translucentRow = [glass, core, shell, inner, beads, tube];
manimScene.add(...opaqueRow, ...translucentRow);
applyManimStyle3D(manimScene);

async function buildUp(): Promise<void> {
const button = document.getElementById('buildBtn') as HTMLButtonElement;
button.disabled = true;
await manimScene.play(
new LaggedStart(
[...opaqueRow, glass, core, shell, inner, beads].map(
(m) => new Create3D(m, { duration: 1.6 }),
),
{ lagRatio: 0.15 },
),
new GrowAlongPath3D(tube, { duration: 2.5 }),
);
button.disabled = false;
}

document.getElementById('buildBtn')!.addEventListener('click', () => void buildUp());

// ── Cartoon preset, white page ────────────────────────────────────────

const cartoonScene = new ThreeDScene(document.getElementById('cartoon')!, {
...CAMERA,
height: 260,
backgroundColor: '#ffffff',
});
const cartoonRow = new Group(
...primitives(0, ['#f2a36b', '#5b6ee1', '#e8603c', '#d94f8c', '#79c7e8']),
);
cartoonScene.add(cartoonRow);
applyToonShading(cartoonRow, 'cartoon');

manimScene.wait(Infinity);
cartoonScene.wait(Infinity);

Learn More: ThreeDScene · Create3D · GrowAlongPath3D · TubeFromPoints · InstancedMobject


Organic 3D Shapes​

The general 3D building blocks of the cell kit, one of each: a bent rod (Capsule3D), a lumpy blob (Blob3D), cut shells with a plane cut and a wedge cut (Shell3D), extruded slabs with a bend or a hole (Extrude3D), a tube net (TubeNetwork3D), a capped filament (TubeFromPoints), and instances scattered on a surface (scatterOnMesh, scatterOnEllipsoid).

Source Code
/**
* Organic 3D shapes: the building blocks of a cutaway cell, one of each.
*
* Back row: a bent rod (Capsule3D), a lumpy nucleolus (Blob3D), a cut bowl
* with a blob inside (Shell3D, plane cut), and a nucleus with a wedge cut and
* bead-ring pores (Shell3D + InstancedMobject + beadRingGeometry).
* Front row: a curved ER sheet dotted with ribosomes (Extrude3D +
* scatterOnMesh), a golgi stack (Extrude3D with a sphere bend), a
* mitochondrion slice with cristae folds (Extrude3D with a hole), a tube net
* (TubeNetwork3D.lattice), and a capped filament (TubeFromPoints).
*
* URL options: `?opacity=0.4` makes every fill translucent, `?reveal=0.5`
* draws only the first half of every organic mesh (its build-up order).
*/
import * as THREE from 'three';
import {
ThreeDScene,
Capsule3D,
Blob3D,
Shell3D,
Extrude3D,
TubeNetwork3D,
TubeFromPoints,
InstancedMobject,
scatterOnMesh,
scatterOnEllipsoid,
toInstances,
beadRingGeometry,
BLUE_B,
BLUE_D,
TEAL_C,
GREEN_C,
YELLOW_D,
GOLD_A,
GOLD_C,
GOLD_E,
RED_A,
RED_C,
RED_D,
MAROON_B,
MAROON_C,
PURPLE_A,
PURPLE_C,
PURPLE_E,
type Mobject,
type Point2D,
type Vector3Tuple,
} from 'manim-web';

const params = new URLSearchParams(location.search);
const OPACITY = Number(params.get('opacity') ?? 1);
const REVEAL = params.has('reveal') ? Number(params.get('reveal')) : null;

const container = document.getElementById('container')!;
const scene = new ThreeDScene(document.getElementById('container'), {
width: 1200,
height: 675,
phi: 58 * (Math.PI / 180),
theta: -72 * (Math.PI / 180),
distance: 15.5,
fov: 32,
});
scene.lighting.addAmbient({ intensity: 0.5 });

// ---- back row -------------------------------------------------------------

const rod = new Capsule3D({
radius: 0.32,
length: 1.8,
bend: Math.PI / 2.5,
direction: [1, 0, 0.3],
center: [-6, 2.2, 0.4],
color: RED_C,
opacity: OPACITY,
});

const nucleolus = new Blob3D({
radius: 0.75,
lobes: 16,
lobeSize: 0.42,
lumpiness: 0.2,
seed: 7,
center: [-3, 2.2, 0.75],
color: MAROON_C,
opacity: OPACITY,
});

const bowl = new Shell3D({
outerRadius: 1.25,
thickness: 0.14,
scale: [1.2, 1, 0.75],
cutOffset: 0.25,
center: [0.2, 2.2, 0.8],
color: GOLD_C,
innerColor: GOLD_E,
rimColor: GOLD_A,
opacity: OPACITY,
});
const inside = new Blob3D({
radius: 0.35,
lobes: 3,
seed: 2,
center: [0.2, 2.2, 0.55],
color: TEAL_C,
});

const NUCLEUS_CENTER: Vector3Tuple = [3.6, 2.2, 1];
const nucleus = new Shell3D({
outerRadius: 1.1,
thickness: 0.12,
cut: 'wedge',
wedgeStart: -Math.PI / 2 - 0.9,
wedgeAngle: 1.8,
center: NUCLEUS_CENTER,
color: PURPLE_C,
innerColor: PURPLE_E,
rimColor: PURPLE_A,
opacity: OPACITY,
});
const pores = new InstancedMobject({
geometry: beadRingGeometry({ beads: 8, radius: 0.07, beadRadius: 0.028 }),
material: new THREE.MeshStandardMaterial({ color: PURPLE_A }),
instances: toInstances(
scatterOnEllipsoid({
count: 70,
radii: 1.105,
center: NUCLEUS_CENTER,
seed: 5,
minDistance: 0.3,
// Skip the removed wedge: it opens toward -Y.
filter: (p) => p.normal[1] > -0.45 || Math.abs(p.normal[0]) > 0.75,
}),
),
});
const innerNucleolus = new Blob3D({
radius: 0.4,
lobes: 12,
lobeSize: 0.4,
seed: 11,
center: NUCLEUS_CENTER,
color: MAROON_C,
});

// ---- front row ------------------------------------------------------------

/** A rounded rectangle outline, centred on the origin. */
function roundedRect(w: number, h: number, r: number, steps = 6): Point2D[] {
const pts: Point2D[] = [];
const corners: [number, number, number][] = [
[w / 2 - r, h / 2 - r, 0],
[-w / 2 + r, h / 2 - r, Math.PI / 2],
[-w / 2 + r, -h / 2 + r, Math.PI],
[w / 2 - r, -h / 2 + r, (3 * Math.PI) / 2],
];
for (const [cx, cy, a0] of corners) {
for (let i = 0; i <= steps; i++) {
const a = a0 + (Math.PI / 2) * (i / steps);
pts.push([cx + r * Math.cos(a), cy + r * Math.sin(a)]);
}
}
return pts;
}

/** An ellipse outline. */
function ellipse(a: number, b: number, n = 48): Point2D[] {
return Array.from({ length: n }, (_, i): Point2D => {
const t = (2 * Math.PI * i) / n;
return [a * Math.cos(t), b * Math.sin(t)];
});
}

const erSheet = new Extrude3D({
outline: roundedRect(2.6, 0.9, 0.35),
depth: 0.16,
bevel: 0.06,
bend: { radius: 1.6 },
center: [-6, -1.6, 0.2],
color: BLUE_D,
opacity: OPACITY,
});
erSheet.rotate(Math.PI / 2, { axis: [1, 0, 0] });
const ribosomes = new InstancedMobject({
geometry: new THREE.SphereGeometry(0.035, 10, 8),
material: new THREE.MeshStandardMaterial({ color: MAROON_B }),
instances: toInstances(scatterOnMesh(erSheet, { count: 300, seed: 3, minDistance: 0.07 }), {
scale: [0.8, 1.3],
}),
});

const golgi: Mobject[] = [0, 1, 2, 3].map(
(i) =>
new Extrude3D({
outline: ellipse(1.0 - 0.12 * i, 0.55 - 0.05 * i),
depth: 0.09,
bevel: 0.04,
bend: { radius: -2, mode: 'sphere' },
center: [-2.9, -1.6, 0.2 + 0.2 * i],
color: i % 2 === 0 ? YELLOW_D : GOLD_C,
opacity: OPACITY,
}),
);

/** Lumen of a mitochondrion: an inner stadium with cristae folds poking in. */
function cristaeHole(a: number, b: number): Point2D[] {
const pts: Point2D[] = [];
const tooth = (x: number, y0: number, dir: 1 | -1, h: number, w: number) => {
// A thin U-shaped fold from the wall at y0 into the lumen.
const tipY = y0 + dir * h;
pts.push([x - (dir * w) / 2, y0], [x - (dir * w) / 2, tipY - dir * (w / 2)]);
for (let k = 1; k < 6; k++) {
const t = Math.PI - (Math.PI * k) / 6;
pts.push([
x + dir * (w / 2) * Math.cos(t),
tipY - dir * (w / 2) + dir * (w / 2) * Math.sin(t),
]);
}
pts.push([x + (dir * w) / 2, tipY - dir * (w / 2)], [x + (dir * w) / 2, y0]);
};
for (const x of [-1.05, -0.25, 0.55]) tooth(x, -b, 1, 0.55, 0.14);
for (let k = 0; k <= 8; k++) {
const t = -Math.PI / 2 + (Math.PI * k) / 8;
pts.push([a + b * Math.cos(t), b * Math.sin(t)]);
}
for (const x of [0.95, 0.15, -0.65]) tooth(x, b, -1, 0.55, 0.14);
for (let k = 0; k <= 8; k++) {
const t = Math.PI / 2 + (Math.PI * k) / 8;
pts.push([-a + b * Math.cos(t), b * Math.sin(t)]);
}
return pts;
}

/** A stadium (rounded-end rod) outline. */
function stadium(a: number, r: number): Point2D[] {
const pts: Point2D[] = [];
for (let k = 0; k <= 12; k++) {
const t = -Math.PI / 2 + (Math.PI * k) / 12;
pts.push([a + r * Math.cos(t), r * Math.sin(t)]);
}
for (let k = 0; k <= 12; k++) {
const t = Math.PI / 2 + (Math.PI * k) / 12;
pts.push([-a + r * Math.cos(t), r * Math.sin(t)]);
}
return pts;
}

const mitochondrion = new Extrude3D({
outline: stadium(1.35, 0.62),
holes: [cristaeHole(1.35, 0.42)],
depth: 0.45,
bevel: 0.05,
center: [0.4, -1.6, 0.3],
color: RED_D,
capColor: RED_A,
opacity: OPACITY,
});

const net = new TubeNetwork3D({
...TubeNetwork3D.lattice({
size: [2.4, 2, 0.5],
spacing: 0.3,
seed: 4,
center: [3.6, -1.6, 0.3],
}),
radius: 0.04,
color: BLUE_B,
opacity: OPACITY,
});

const filament = new TubeFromPoints({
points: Array.from({ length: 9 }, (_, i): Vector3Tuple => [
5.6 + 0.2 * Math.sin(i),
-2.6 + 0.45 * i,
0.3 + 0.25 * Math.cos(1.3 * i),
]),
radius: 0.05,
capped: true,
color: GREEN_C,
opacity: OPACITY,
});

const all: Mobject[] = [
rod,
nucleolus,
inside,
bowl,
innerNucleolus,
nucleus,
pores,
erSheet,
ribosomes,
...golgi,
mitochondrion,
net,
filament,
];
scene.add(...all);

// Draw-range reveal check: each organic mesh shows its first REVEAL fraction.
if (REVEAL !== null) {
for (const m of all) {
m.getThreeObject().traverse((o) => {
if (!(o instanceof THREE.Mesh) || o instanceof THREE.InstancedMesh) return;
const index = o.geometry.getIndex();
if (!index || !o.geometry.getAttribute('reveal')) return;
o.geometry.setDrawRange(0, Math.floor((REVEAL * index.count) / 3) * 3);
});
}
}

scene.wait(Infinity);

Learn More: Capsule3D · Blob3D · Shell3D · Extrude3D · TubeNetwork3D · InstancedMobject


Explainer Tour (Camera Focus, Captions, Callouts)​

The direction layer of a 3D explainer. ExplainerTour runs a list of stops; per stop it dims everything but the target (FocusDim), moves the camera (CameraFocus) and swaps the caption (CaptionCard) in one parallel play, then draws callouts (Callout3D), a close-up inset (InsetPanel) and a focus ring, and runs your own animations.

Source Code
import {
BLUE,
Cube,
ExplainerTour,
GOLD,
Membrane,
Rotate,
RED,
Sphere,
ThreeDScene,
Torus,
type TourTarget,
} from 'manim-web';

// A narrated tour over three plain solids, built from the direction layer:
// ExplainerTour composes FocusDim + CameraFocus + CaptionCard per stop, then
// Callout3D / InsetPanel annotations and the author's own animations.

const container = document.getElementById('container')!;
const scene = new ThreeDScene(document.getElementById('container'), {
width: 720,
height: 720,
frameWidth: 8,
frameHeight: 8,
backgroundColor: '#0F1115',
phi: 1.15,
theta: -Math.PI / 2,
distance: 14,
fov: 35,
enableOrbitControls: false,
});
scene.lighting.addAmbient({ intensity: 0.5 });

const sphere = new Sphere({ radius: 1, color: BLUE, center: [-2.6, 0, 0] });
const torus = new Torus({ radius: 0.9, tubeRadius: 0.3, color: GOLD, center: [0, 0.4, 0] });
const cube = new Cube({ sideLength: 1.4, color: RED, center: [2.6, 0, 0] }) as Cube & TourTarget;
cube.rotate(0.6, [0, 0, 1]);

// A target can carry its own tour defaults (a 3D kit implements TourTarget).
cube.getCaption = () => ({
title: 'Cube',
swatch: RED,
body: 'Six square faces. Its wall, seen up close, is a lipid bilayer in this toy model.',
});
cube.getFocusFraming = () => ({ fill: 0.38, phi: 1.0, theta: -1.2, screenOffset: [-1.3, 0.6] });

scene.add(sphere, torus, cube);

const tour = new ExplainerTour(scene);

await scene.wait(0.3);
await tour.run([
{
caption: { title: 'Three solids', body: 'A short tour in manim style.', style: 'headline' },
reveal: 'all',
dim: false,
hold: 0.8,
},
{
target: sphere,
framing: { fill: 0.42, screenOffset: [0.8, 0.9], phi: 1.05 },
caption: {
title: 'Sphere',
swatch: BLUE,
body: 'Every point on the surface is one radius from the centre.',
footnote: 'Drawn with 32 segments around.',
},
emphasis: 'ring',
hold: 0.6,
},
{
target: torus,
framing: { fill: 0.45, phi: 0.75, theta: -1.9, screenOffset: [0, 0.8] },
caption: { title: 'Torus', swatch: GOLD, body: 'A circle swept around an axis.' },
// The author hook: any animation of your own. The torus tilts, and the
// callouts, anchored to points on it, follow.
onEnter: async (_scene, _stop, player) => {
await player.play(new Rotate(torus, { angle: 0.7, axis: [1, 0, 0], duration: 1.5 }));
},
callouts: [
{ label: 'tube', anchor: torus, anchorLocal: [0.9, 0, 0.3], direction: [1, 0.7] },
{
label: 'R = 0.9',
tex: true,
anchor: torus,
anchorLocal: [-0.9, 0, 0],
direction: [-1, 0.8],
leader: 'elbow',
},
],
hold: 1,
},
{
target: cube,
inset: {
title: 'Close-up',
anchor: [2.6 + 0.7, 0, 0.3],
content: [new Membrane({ length: 6, spacing: 0.35 })],
position: [2.1, 1.6],
width: 3.2,
height: 2.2,
},
hold: 1.2,
},
{
target: [0, 0, 0],
framing: { distance: 13, phi: 1.15, theta: -Math.PI / 2 },
dim: false,
caption: {
title: 'Solids',
rows: [
{ color: BLUE, text: 'Sphere: one radius' },
{ color: GOLD, text: 'Torus: a swept circle' },
{ color: RED, text: 'Cube: six faces' },
],
},
hold: 1.2,
},
]);
await tour.finish();
tour.dispose();

Learn More: ExplainerTour · CameraFocus · FocusDim · CaptionCard · Callout3D · InsetPanel · FocusRing


Narrated Video Export​

Two pre-recorded narration clips and a quiet music bed, placed on the audio timeline at the current scene time with narrate() and AudioManager.addSound(). registerRender() opts the page in to command-line rendering, so npm run render writes an mp4 with the audio in sync with the frames.

Runs locally

This example plays narration files from examples/audio/, so it has no live embed on this page. Source: examples/narrated_export.ts.

Run it with sound: npm run dev, then open /examples/narrated_export.html. Render it to a file:

npm run render -- narrated_export --width 1080 --height 1080 --fps 30 --bitrate 6000000 --out narrated_export.mp4
Source Code
import {
Scene,
Circle,
Square,
Create,
Transform,
narrate,
registerRender,
BLUE,
GREEN,
} from 'manim-web';

// Narrated export: two narration clips and a quiet music bed, placed on the
// audio timeline at "now", so a video export holds them in sync with the frames.
// Render it to a file with:
// node scripts/render-example.mjs narrated_export --width 1080 --height 1080 --fps 30 --out out.mp4

const LINE_1 = './audio/narrated_export_line1.mp3';
const LINE_2 = './audio/narrated_export_line2.mp3';
const MUSIC = './audio/narrated_export_music.mp3';

const container = document.getElementById('container')!;
const scene = new Scene(document.getElementById('container'), {
width: 800,
height: 450,
backgroundColor: '#000000',
});
// Opt in to command-line rendering (scripts/render-example.mjs).
registerRender(scene, { construct: narratedExport });

const playBtn = document.getElementById('playBtn') as HTMLButtonElement;

playBtn.addEventListener('click', async () => {
if (isAnimating) return;
isAnimating = true;
playBtn.disabled = true;

isAnimating = false;
playBtn.disabled = false;
});

document.getElementById('resetBtn')!.addEventListener('click', () => {
scene.clear();
scene.audioManager.clearTracks();
});

Learn More: AudioManager · WebCodecsExporter


3D Organelles​

Every organelle class of the 3D cell kit, each one alone with its name: membrane, nucleus, nuclear pore, rough and smooth ER, Golgi apparatus, a cutaway mitochondrion, ribosome, lysosome, peroxisome, centrosome and cytoskeleton. Each one is a group of named parts in the manim look and plays its own staged build-up.

Source Code
/**
* The organelles of the 3D cell kit, each one alone with its name.
*
* Every class is a group of named parts in the manim look (bright rim stroke
* over a soft body), deterministic for its seed. Drag to orbit.
*
* URL options: `?only=<index>` shows one organelle at full size,
* `?detail=low|medium|high`, `?build` plays every build-up.
*/
import {
ThreeDScene,
Text,
LaggedStart,
CellMembrane3D,
Nucleus3D,
NuclearPore3D,
RoughER3D,
SmoothER3D,
GolgiApparatus3D,
Mitochondrion3D,
Ribosome3D,
Vesicle3D,
Centrosome3D,
Cytoskeleton3D,
type CellDetail,
type Organelle3D,
type Vector3Tuple,
} from 'manim-web';

const params = new URLSearchParams(location.search);
const detail = (params.get('detail') ?? 'medium') as CellDetail;
const only = params.has('only') ? Number(params.get('only')) : null;

const container = document.getElementById('container')!;
const scene = new ThreeDScene(document.getElementById('container'), {
width: 1600,
height: 1000,
phi: 1.12,
theta: -Math.PI / 2,
distance: only === null ? 20 : 7,
fov: 34,
enableOrbitControls: true,
});
scene.lighting.addAmbient({ intensity: 0.55 });

/** The gallery: a factory per organelle, so `?only` builds just one. */
const entries: [string, (c: Vector3Tuple) => Organelle3D][] = [
['Cell membrane', (c) => new CellMembrane3D({ radius: 1.2, center: c, detail })],
['Nucleus', (c) => new Nucleus3D({ radius: 1.05, center: c, detail })],
['Nuclear pore', (c) => new NuclearPore3D({ size: 0.36, center: c, detail })],
[
'Rough ER',
(c) => new RoughER3D({ innerRadius: 0.55, spacing: 0.24, height: 0.7, center: c, detail }),
],
['Smooth ER', (c) => new SmoothER3D({ size: [2.3, 1.5, 0.5], center: c, detail })],
[
'Golgi apparatus',
(c) => new GolgiApparatus3D({ size: 1.7, direction: [1, -0.45, 0], center: c, detail }),
],
[
'Mitochondrion',
(c) => new Mitochondrion3D({ length: 2.1, radius: 0.42, cutaway: true, center: c, detail }),
],
['Ribosome', (c) => new Ribosome3D({ size: 0.8, center: c, detail })],
['Lysosome', (c) => Vesicle3D.lysosome({ radius: 0.6, center: c, detail })],
['Peroxisome', (c) => Vesicle3D.peroxisome({ radius: 0.55, center: c, detail })],
['Centrosome', (c) => new Centrosome3D({ size: 0.9, center: c, detail })],
[
'Cytoskeleton',
(c) =>
new Cytoskeleton3D({ radii: [1.35, 1.15, 0.7], origin: [0.1, 0.1, 0], center: c, detail }),
],
];

const COLS = 4;
const shown = only === null ? entries : [entries[only]];
const organelles: Organelle3D[] = [];
shown.forEach(([name, make], i) => {
const col = i % COLS;
const row = Math.floor(i / COLS);
const center: Vector3Tuple = only === null ? [(col - 1.5) * 3.7, 0, (1 - row) * 3.5] : [0, 0, 0];
const organelle = make(center);
organelles.push(organelle);
scene.add(organelle);
const label = new Text({ text: name, fontSize: only === null ? 22 : 30, color: '#ECEFF4' });
label.moveTo([center[0], center[1], center[2] - (only === null ? 1.45 : 1.9)]);
scene.add(label);
scene.addFixedOrientationMobjects(label);
});

if (params.has('build')) {
await scene.play(
new LaggedStart(
organelles.map((o) => o.buildAnimation()),
{ lagRatio: 0.15 },
),
);
}

Learn More: Organelle3D · Nucleus3D · Mitochondrion3D · GolgiApparatus3D · RoughER3D · Ribosome3D · Vesicle3D


3D Animal Cell​

A cutaway animal cell from one line, new Cell3D({ preset: "animal" }): the organelles are placed without overlap inside a cut-open membrane. The cell builds up one organelle at a time, then a CellTour (an ExplainerTour that also clears the free ribosomes in front of each focused organelle) visits the nucleus, the Golgi apparatus and a mitochondrion with their default captions and one named callout each.

Source Code
/**
* A cutaway animal cell from the 3D cell kit.
*
* `new Cell3D({ preset: 'animal' })` places the nucleus, rough and smooth ER,
* Golgi, centrosome, mitochondria, lysosomes, peroxisomes, vesicles and a
* crowd of free ribosomes inside a cut-open membrane. Drag to orbit.
* "Build the cell" plays `cell.buildAnimation()` (one organelle at a time),
* then a short CellTour (an ExplainerTour that clears the free ribosomes in
* front of each organelle) over three organelles with their default
* captions and one named callout each.
*
* URL options: `?detail=low|medium|high`, `?cutaway=bowl|wedge|none`,
* `?cytoskeleton`, `?auto` (play on load).
*/
import {
ThreeDScene,
Cell3D,
CellTour,
registerRender,
type CellCutaway,
type CellDetail,
} from 'manim-web';

const params = new URLSearchParams(location.search);
const container = document.getElementById('container')!;
const scene = new ThreeDScene(document.getElementById('container'), {
width: 1080,
height: 1080,
frameWidth: 14,
frameHeight: 14,
backgroundColor: '#11131A',
phi: 0.92,
theta: -1.2,
distance: 18.5,
fov: 30,
enableOrbitControls: true,
});
scene.lighting.addAmbient({ intensity: 0.55 });

const cell = new Cell3D({
radius: 4,
preset: 'animal',
detail: (params.get('detail') ?? 'medium') as CellDetail,
cutaway: (params.get('cutaway') ?? 'bowl') as CellCutaway,
cytoskeleton: params.has('cytoskeleton'),
seed: 3,
});
scene.add(cell);

const START = { phi: 0.92, theta: -1.2, distance: 18.5 };

async function construct(s: ThreeDScene): Promise<void> {
s.setCameraOrientation(START.phi, START.theta, START.distance);
await s.play(cell.buildAnimation({ duration: 12 }));
await s.wait(0.5);

const tour = new CellTour(s, cell);
await tour.run([
{
target: cell.getOrganelle('nucleus'),
callouts: [{ label: 'nuclear pore', anchor: 'pore', direction: [1, 0.7] }],
hold: 1.5,
},
{
target: cell.getOrganelle('golgi apparatus'),
callouts: [{ label: 'entry side', anchor: 'entrySide', direction: [-1, 0.7] }],
hold: 1.5,
},
{
target: cell.getOrganelle('mitochondrion'),
callouts: [{ label: 'cristae', anchor: 'cristae', direction: [1, 0.8] }],
hold: 1.5,
},
]);
await tour.finish();
await s.focusOn([0, 0, 0], {
phi: START.phi,
theta: START.theta,
distance: START.distance,
runTime: 2,
});
}

// Opt in to command-line rendering (scripts/render-example.mjs).
registerRender(scene, { construct });

const playBtn = document.getElementById('playBtn') as HTMLButtonElement;
playBtn.addEventListener('click', async () => {
playBtn.disabled = true;
await construct(scene);
playBtn.disabled = false;
});
if (params.has('auto') || params.has('embed')) setTimeout(() => playBtn.click(), 300);

Learn More: Cell3D · CellTour · Organelle3D · ExplainerTour


3D Cell Tour (Narrated)​

The narrated showcase of the 3D cell kit: a full tour of a cutaway animal cell with a recorded voice track, captions, callouts, insets and the process animations (mRNA export, protein translation, the secretory route, ATP release, cargo on a microtubule). CellTour runs the stops; each stop starts its narration clip with narrate() and lasts at least as long as the clip.

Runs locally

This example plays narration files from examples/audio/, so it has no live embed on this page. Source: examples/cell_tour_3d.ts.

Run it with sound: npm run dev, then open /examples/cell_tour_3d.html. Render it to a file:

npm run render -- cell_tour_3d --width 1080 --height 1080 --fps 30 --bitrate 6000000 --out cell_tour_3d.mp4

Learn More: Cell3D · CellTour · ExplainerTour · CameraFocus · CaptionCard