Introduction to Theatre.js
Theatre.js is a powerful animation library designed for creating and controlling animations in JavaScript, particularly for Three.js scenes. It provides a timeline-based approach, allowing users to keyframe animations and manage complex sequences with an intuitive UI.
Why Use Theatre.js with Three.js?
Three.js provides a solid foundation for rendering 3D graphics, but its native animation system can be cumbersome for handling intricate animations. Theatre.js integrates smoothly with Three.js, offering:
- A visual editor for keyframing animations.
- Precise control over object transformations (position, rotation, scale, and more).
- Scene state management, allowing users to tweak parameters dynamically.
- Efficient timeline-based sequencing.
Setting Up Theatre.js with Three.js
To start using Theatre.js with Three.js, install it via npm:
npm install @theatre/core
Then, import and set up a simple Theatre.js studio:
import * as THREE from 'three';
import { getProject, types } from '@theatre/core';
// Create a Theatre.js project
const project = getProject('MyThreeJSProject');
// Create a sheet (like a timeline for animations)
const sheet = project.sheet('MainScene');
// Define an object in Theatre.js for animation
const cubeObj = sheet.object('Cube', {
position: types.compound({
x: types.number(0, { range: [-5, 5] }),
y: types.number(0, { range: [-5, 5] }),
z: types.number(0, { range: [-5, 5] })
})
});
Animating Objects in Three.js with Theatre.js
Theatre.js can be used to animate Three.js objects by linking their properties:
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
camera.position.z = 5;
// Syncing Theatre.js animation with Three.js
cubeObj.onValuesChange((values) => {
cube.position.set(values.position.x, values.position.y, values.position.z);
});
// Animation loop
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
Advanced Features
- Easing & Keyframes: Theatre.js supports smooth easing and precise keyframe control.
- UI for Adjustments: It provides an interactive UI for tweaking animations without modifying code.
- Multiple Object Animations: You can animate multiple Three.js objects simultaneously.
Conclusion
Theatre.js is an excellent tool for animating Three.js scenes with a more structured and interactive approach. Whether you’re creating complex animations or just need an intuitive timeline editor, Theatre.js simplifies the process, making it a valuable addition to any Three.js project.