Algorithm Animation with Remotion
Create professional algorithm visualization videos using React and Remotion.
Quick Start
IMPORTANT: Before starting, ask the user:
- •
Programming Language for code examples:
- •JavaScript/TypeScript (推荐 - Remotion uses React/TypeScript)
- •Python
- •C++
- •Java
- •其他 (用户指定)
- •
Natural Language for explanations:
- •中文 (Chinese)
- •English
- •双语 (Bilingual - Chinese + English)
When a user requests an algorithm animation:
- •Ask for programming language preference (JavaScript/Python/C++/Java/etc.)
- •Ask for natural language preference (中文/English/双语)
- •Initialize project using the init script
- •Generate component for the specific algorithm
- •Implement algorithm logic using reference patterns with chosen languages
- •Preview and render the video
Supported Algorithm Types
- •Sorting: Bubble sort, quick sort, merge sort, insertion sort, selection sort, heap sort
- •Searching: Binary search, linear search, DFS, BFS
- •Tree: Tree traversal (in-order, pre-order, post-order), BST operations
- •Graph: Dijkstra's algorithm, Bellman-Ford, Kruskal, Prim, topological sort
- •Dynamic Programming: Fibonacci, knapsack, LCS, edit distance
Workflow
Step 1: Initialize Remotion Project
bash scripts/init_project.sh <project-name> cd <project-name>
Or manually copy files from assets/remotion-template/ to the project directory.
Step 2: Generate Algorithm Component
Standard Mode (basic visualization):
python3 scripts/generate_component.py <algorithm-type> <algorithm-name>
Educational Mode (with detailed explanations and code):
python3 scripts/generate_component.py <algorithm-type> <algorithm-name> --educational
Algorithm types: sorting, searching, tree, graph, dp
Examples:
# Standard mode python3 scripts/generate_component.py sorting bubble-sort # Educational mode with explanations python3 scripts/generate_component.py sorting bubble-sort --educational python3 scripts/generate_component.py searching binary-search --educational python3 scripts/generate_component.py tree in-order-traversal --educational
Educational mode generates components with:
- •Introduction slides explaining the algorithm
- •Step-by-step text descriptions
- •Code snippets with line highlighting
- •Slower pacing with longer frame durations
- •Educational annotations
Step 3: Implement Algorithm Logic
Consult the reference files for implementation patterns:
- •Sorting algorithms: See references/sorting.md
- •Searching algorithms: See references/searching.md
- •Tree & graph algorithms: See references/tree-graph.md
- •Dynamic programming: See references/dynamic-programming.md
- •Educational animations: See references/educational-animations.md for detailed explanations, code display, and pacing
Each reference file contains:
- •Step generation patterns
- •Complete algorithm implementations
- •Visualization code
- •Color schemes
- •Animation effects
For educational animations, see the educational-animations reference for:
- •Introduction slide patterns
- •Step descriptions with code references
- •Variable timing for different step types
- •Code highlighting components
- •Best practices for pacing and explanations
Step 4: Register Composition
Add the component to src/Root.tsx:
import { Composition } from 'remotion';
import { BubbleSort } from './BubbleSort';
export const RemotionRoot: React.FC = () => {
return (
<>
<Composition
id="BubbleSort"
component={BubbleSort}
durationInFrames={300}
fps={30}
width={1920}
height={1080}
defaultProps={{
arraySize: 10,
}}
/>
</>
);
};
Step 5: Preview and Render
Preview (opens Remotion Studio):
npm start
Render video:
npm run build BubbleSort out/bubble-sort.mp4
Common Patterns
Animation Structure
All algorithm animations follow this pattern:
interface AlgorithmStep {
// Current state
data: any;
// Highlighted elements
active: number[];
// Completed elements
completed: number[];
}
// 1. Generate steps
const steps = useMemo(() => generateSteps(initialData), [initialData]);
// 2. Calculate current step
const currentStepIndex = Math.floor(frame / framesPerStep);
const currentStep = steps[currentStepIndex];
// 3. Render visualization based on current step
return <Visualization step={currentStep} />;
Color Scheme
Use consistent colors across all animations:
- •Green (
#16a085): Default/unprocessed - •Red (
#e74c3c): Currently active/comparing - •Orange (
#f39c12): Swapping/moving - •Blue (
#3498db): Completed/sorted - •Purple (
#9b59b6): Special (pivot, target, etc.) - •Yellow (
#f1c40f): Queue/frontier - •Gray (
#555): Inactive/out of range
Timing
Standard animations:
const framesPerStep = Math.floor(durationInFrames / steps.length); const currentStepIndex = Math.min( Math.floor(frame / framesPerStep), steps.length - 1 );
Educational animations (variable timing):
// Each step can have custom duration
interface DetailedStep {
// ... other fields
duration?: number; // Frames for this step
}
// Recommended durations at 30fps:
// - Simple comparisons: 30-45 frames (1-1.5s)
// - Important operations: 60 frames (2s)
// - Round completion: 60-90 frames (2-3s)
// - Introduction slides: 90 frames (3s)
Spring Animations
const scale = spring({
frame: frame % framesPerStep,
fps,
config: { damping: 200, stiffness: 200, mass: 1 },
});
Customization
Modify these parameters in compositions:
- •
durationInFrames: Total video length (e.g., 300 = 10 seconds at 30fps)- •Standard animations: 300-450 frames (10-15 seconds)
- •Educational animations: 600-900+ frames (20-30+ seconds for detailed explanations)
- •
fps: Frames per second (typically 30 or 60) - •
width,height: Video dimensions (e.g., 1920x1080) - •
defaultProps: Algorithm-specific parameters (array size, target value, etc.)
Educational Components
The template includes reusable educational components in assets/remotion-template/src/components/ExplanationComponents.tsx:
ExplanationPanel
Display text explanations with fade in/out and scale animation:
<ExplanationPanel
title="Algorithm Overview"
content="Bubble sort repeatedly compares adjacent elements..."
startFrame={0}
endFrame={90}
position="center" // 'top' | 'bottom' | 'left' | 'right' | 'center'
size="large" // Optional: 'small' | 'medium' | 'large' (auto-adjusts based on content)
/>
Features:
- •Dynamic font sizing: Automatically adjusts based on content length
- •Large (< 60 chars): 72px title, 40px content
- •Medium (60-100 chars): 52px title, 32px content
- •Small (> 100 chars): 36px title, 24px content
- •Center position: Best for introduction slides (more prominent)
- •Scale animation: Smooth entrance effect (0.9 → 1.0)
CodeHighlight
Show code with line highlighting and multi-language support:
<CodeHighlight
code={algorithmCode}
highlightedLine={5} // Which line to highlight
startFrame={100}
endFrame={200}
language="cpp" // 'typescript' | 'javascript' | 'python' | 'cpp' | 'java'
/>
Supported languages:
- •JavaScript/TypeScript
- •Python
- •C++
- •Java
See references/code-languages.md for code examples in different languages.
StepDescription
Display current step information:
<StepDescription step="Comparing Elements" description="比较 arr[2] 和 arr[3]" codeReference="Line 12-15" />
Content Verification (CRITICAL)
IMPORTANT: Always verify the correctness of animations before finalizing:
1. Save Algorithm Code
After creating the animation, save the displayed code to a file:
# Create algorithm-code file in the project directory # Example: algorithm-code.cpp, algorithm-code.py, etc.
2. Create Verification Document
Create a VERIFICATION.md file with the following sections:
a) Algorithm Structure Validation
- •Verify data structure is correct (tree, array, graph, etc.)
- •Check initial values match the algorithm logic
- •Confirm edge cases are handled
b) Algorithm Logic Validation
- •Verify each step follows the algorithm correctly
- •Check loop conditions and termination
- •Validate update operations (swap, insert, delete, etc.)
- •Confirm sorting/searching criteria
c) Manual Execution Test
- •Walk through the algorithm manually with the same input
- •Compare expected vs. actual results at each step
- •Verify final output is correct
d) Code Line Reference Validation
- •Ensure all
codeReferenceandcodeLinevalues are accurate - •Check that highlighted lines match the current operation
- •Verify code syntax is correct for the chosen language
e) Educational Content Validation
- •Verify all explanations are accurate
- •Check terminology is correct
- •Confirm complexity analysis is right (Big-O notation)
- •Validate algorithmic concepts
f) Visual Animation Validation
- •Check color coding is consistent
- •Verify state transitions are logical
- •Ensure no steps are skipped or duplicated
3. Create Project Summary
Create a PROJECT-SUMMARY.md documenting:
- •Algorithm information
- •File structure
- •Animation content breakdown
- •Build instructions
- •Verification results
Example Verification Checklist:
| Component | Status | |-----------|--------| | Data structure | ✅ Correct | | Algorithm logic | ✅ Correct | | Final result | ✅ Correct (value: X) | | Code line numbers | ✅ Accurate | | Explanations | ✅ Accurate | | Visual design | ✅ Clear |
Never skip verification! Incorrect algorithm animations can mislead learners.
Tips
- •Start with references: Copy implementation patterns from reference files
- •Test incrementally: Use Remotion Studio to preview changes in real-time
- •Keep steps granular: More steps = smoother animation
- •Add titles and labels: Make videos educational with clear annotations
- •Use consistent styling: Follow the color scheme for visual consistency
- •Always verify correctness: Create verification documents for every animation
- •Save algorithm code: Keep code files for reference and documentation
Troubleshooting
Animations too fast/slow: Adjust durationInFrames or frames per step calculation
Incorrect rendering: Check step generation logic, ensure all states are captured
TypeScript errors: Verify imports and type definitions, check tsconfig.json
Video rendering fails: Ensure all dependencies are installed: npm install
Algorithm behaves incorrectly: Review VERIFICATION.md and manually trace execution