Skip to content

Visualize Your Ideas With Code

docs: add missing sections (#160)

Jacobba8fa9dc0146
diff --git a/packages/2d/src/components/Layout.ts b/packages/2d/src/components/Layout.ts
index 69459a7c..bbd2894f 100644
--- a/packages/2d/src/components/Layout.ts
+++ b/packages/2d/src/components/Layout.ts
@@ -288,6 +288,55 @@ export class Layout extends Node {
lock && this.releaseSize();
}
+ /**
+ * Represents the size of this node.
+ *
+ * @remarks
+ * A size is a two-dimensional vector, where `x` represents the width, and `y`
+ * represents the `height`.
+ *
+ * The value of both x and y is of type {@link partials~Length} which is
+ * either:
+ * - `number` - the desired length in pixels
+ * - `${number}%` - a string with the desired length in percents, for example
+ * `'50%'`
+ * - `null` - an automatic length
+ *
+ * When retrieving the size, all units are converted to pixels, using the
+ * current state of the layout. For example, retrieving the width set to
+ * `'50%'`, while the parent has a width of `200px` will result in the number
+ * `100` being returned.
+ *
+ * When the node is not part of the layout, setting its size using percents
+ * refers to the size of the entire scene.
+ *
+ * @example
+ * Initializing the size:
+ * ```tsx
+ * // with a possible vector:
+ * <Node size={['50%', 200]} />
+ * // with individual components:
+ * <Node width={'50%'} height={200} />
+ * ```
+ *
+ * Accessing the size:
+ * ```tsx
+ * // retrieving the vector:
+ * const size = node.size();
+ * // retrieving an individual component:
+ * const width = node.size.x();
+ * ```
+ *
+ * Setting the size:
+ * ```tsx
+ * // with a possible vector:
+ * node.size(['50%', 200]);
+ * node.size(() => ['50%', 200]);
+ * // with individual components:
+ * node.size.x('50%');
+ * node.size.x(() => '50%');
+ * ```
+ */
@cloneable(false)
@initial({x: null, y: null})
@vector2Signal({x: 'width', y: 'height'})
@@ -343,6 +392,21 @@ export class Layout extends Node {
this.size(value);
}
+ /**
+ * Represents the offset of this node's origin.
+ *
+ * @remarks
+ * By default, the origin of a node is located at its center. The origin
+ * serves as the pivot point when rotating and scaling a node, but it doesn't
+ * affect the placement of its children.
+ *
+ * The value is relative to the size of this node. A value of `1` means as far
+ * to the right/bottom as possible. Here are a few examples of offsets:
+ * - `[-1, -1]` - top left corner
+ * - `[1, -1]` - top right corner
+ * - `[0, 1]` - bottom edge
+ * - `[-1, 1]` - bottom left corner
+ */
@vector2Signal('offset')
public declare readonly offset: Vector2Signal<this>;
@@ -504,7 +568,7 @@ export class Layout extends Node {
result.push(child);
elements.push(child.element);
} else if (child) {
- queue.push(...child.children());
+ queue.unshift(...child.children());
}
}
this.element.replaceChildren(...elements);
diff --git a/packages/2d/src/components/Node.ts b/packages/2d/src/components/Node.ts
index c55742c3..417990a4 100644
--- a/packages/2d/src/components/Node.ts
+++ b/packages/2d/src/components/Node.ts
@@ -70,9 +70,55 @@ export interface NodeProps {
export class Node implements Promisable<Node> {
public declare isClass: boolean;
+ /**
+ * Represents the position of this node in local space of its parent.
+ *
+ * @example
+ * Initializing the position:
+ * ```tsx
+ * // with a possible vector:
+ * <Node position={[1, 2]} />
+ * // with individual components:
+ * <Node x={1} y={2} />
+ * ```
+ *
+ * Accessing the position:
+ * ```tsx
+ * // retrieving the vector:
+ * const position = node.position();
+ * // retrieving an individual component:
+ * const x = node.position.x();
+ * ```
+ *
+ * Setting the position:
+ * ```tsx
+ * // with a possible vector:
+ * node.position([1, 2]);
+ * node.position(() => [1, 2]);
+ * // with individual components:
+ * node.position.x(1);
+ * node.position.x(() => 1);
+ * ```
+ */
@vector2Signal()
public declare readonly position: Vector2Signal<this>;
+ /**
+ * A helper signal for operating on the position in world space.
+ *
+ * @remarks
+ * Retrieving the position using this signal returns the position in world
+ * space. Similarly, setting the position using this signal transforms the
+ * new value to local space.
+ *
+ * If the new value is a function, the position of this node will be
+ * continuously updated to always match the position returned by the function.
+ * This can be useful to "pin" the node in a specific place or to make it
+ * follow another node's position.
+ *
+ * Unlike {@link position}, this signal is not compound - it doesn't contain
+ * separate signals for the `x` and `y` components.
+ */
@wrapper(Vector2)
@cloneable(false)
@signal()
@@ -91,10 +137,24 @@ export class Node implements Promisable<Node> {
}
}
+ /**
+ * Represents the rotation (in degrees) of this node relative to its parent.
+ */
@initial(0)
@signal()
public declare readonly rotation: SimpleSignal<number, this>;
+ /**
+ * A helper signal for operating on the rotation in world space.
+ *
+ * @remarks
+ * Retrieving the rotation using this signal returns the rotation in world
+ * space. Similarly, setting the rotation using this signal transforms the
+ * new value to local space.
+ *
+ * If the new value is a function, the rotation of this node will be
+ * continuously updated to always match the rotation returned by the function.
+ */
@cloneable(false)
@signal()
public declare readonly absoluteRotation: SimpleSignal<number, this>;
@@ -112,10 +172,54 @@ export class Node implements Promisable<Node> {
}
}
+ /**
+ * Represents the scale of this node in local space of its parent.
+ *
+ * @example
+ * Initializing the scale:
+ * ```tsx
+ * // with a possible vector:
+ * <Node scale={[1, 2]} />
+ * // with individual components:
+ * <Node scaleX={1} scaleY={2} />
+ * ```
+ *
+ * Accessing the scale:
+ * ```tsx
+ * // retrieving the vector:
+ * const scale = node.scale();
+ * // retrieving an individual component:
+ * const scaleX = node.scale.x();
+ * ```
+ *
+ * Setting the scale:
+ * ```tsx
+ * // with a possible vector:
+ * node.scale([1, 2]);
+ * node.scale(() => [1, 2]);
+ * // with individual components:
+ * node.scale.x(1);
+ * node.scale.x(() => 1);
+ * ```
+ */
@initial(Vector2.one)
@vector2Signal('scale')
public declare readonly scale: Vector2Signal<this>;
+ /**
+ * A helper signal for operating on the scale in world space.
+ *
+ * @remarks
+ * Retrieving the scale using this signal returns the scale in world space.
+ * Similarly, setting the scale using this signal transforms the new value to
+ * local space.
+ *
+ * If the new value is a function, the scale of this node will be continuously
+ * updated to always match the position returned by the function.
+ *
+ * Unlike {@link scale}, this signal is not compound - it doesn't contain
+ * separate signals for the `x` and `y` components.
+ */
@wrapper(Vector2)
@cloneable(false)
@signal()
@@ -292,6 +396,21 @@ export class Node implements Promisable<Node> {
}
}
+ /**
+ * Get the local-to-world matrix for this node.
+ *
+ * @remarks
+ * This matrix transforms vectors from local space of this node to world
+ * space.
+ *
+ * @example
+ * Calculate the absolute position of a point located 200 pixels to the right
+ * of the node:
+ * ```ts
+ * const local = new Vector2(0, 200);
+ * const world = local.transformAsPoint(node.localToWorld());
+ * ```
+ */
@computed()
public localToWorld(): DOMMatrix {
const parent = this.parent();
@@ -300,16 +419,45 @@ export class Node implements Promisable<Node> {
: this.localToParent();
}
+ /**
+ * Get the world-to-local matrix for this node.
+ *
+ * @remarks
+ * This matrix transforms vectors from world space to local space of this
+ * node.
+ *
+ * @example
+ * Calculate the position relative to this node for a point located in the
+ * top-left corner of the screen:
+ * ```ts
+ * const world = new Vector2(0, 0);
+ * const local = world.transformAsPoint(node.worldToLocal());
+ * ```
+ */
@computed()
public worldToLocal() {
return this.localToWorld().inverse();
}
+ /**
+ * Get the world-to-parent matrix for this node.
+ *
+ * @remarks
+ * This matrix transforms vectors from world space to local space of this
+ * node's parent.
+ */
@computed()
public worldToParent(): DOMMatrix {
return this.parent()?.worldToLocal() ?? new DOMMatrix();
}
+ /**
+ * Get the local-to-parent matrix for this node.
+ *
+ * @remarks
+ * This matrix transforms vectors from local space of this node to local space
+ * of this node's parent.
+ */
@computed()
public localToParent(): DOMMatrix {
const matrix = new DOMMatrix();
@@ -575,11 +723,11 @@ export class Node implements Promisable<Node> {
/**
* Change the parent of this node while keeping the absolute transform.
- *
+ *
* @remarks
* After performing this operation, the node will stay in the same place
* visually, but its parent will be changed.
- *
+ *
* @param newParent - The new parent of this node.
*/
public reparent(newParent: Node) {
@@ -822,7 +970,7 @@ export class Node implements Promisable<Node> {
*/
protected setupDrawFromCache(context: CanvasRenderingContext2D) {
context.globalCompositeOperation = this.compositeOperation();
- context.globalAlpha = this.opacity();
+ context.globalAlpha *= this.opacity();
if (this.hasFilters()) {
context.filter = this.filterString();
}
diff --git a/packages/2d/src/partials/types.ts b/packages/2d/src/partials/types.ts
index 24601584..009e6668 100644
--- a/packages/2d/src/partials/types.ts
+++ b/packages/2d/src/partials/types.ts
@@ -36,6 +36,16 @@ export type TextWrap = boolean | 'pre' | null;
export type LayoutMode = boolean | null;
+/**
+ * Represents a length used by most layout properties.
+ *
+ * @remarks
+ * The value can be either:
+ * - `number` - the desired length in pixels
+ * - `${number}%` - a string with the desired length in percents, for example
+ * `'50%'`
+ * - `null` - an automatic length (equivalent to `auto` in CSS)
+ */
export type Length = number | `${number}%` | null;
export type PossibleCanvasStyle = null | PossibleColor | Gradient | Pattern;
diff --git a/packages/core/src/Project.ts b/packages/core/src/Project.ts
index 8d74e428..59c5979c 100644
--- a/packages/core/src/Project.ts
+++ b/packages/core/src/Project.ts
@@ -263,7 +263,7 @@ export class Project {
this.context.fillRect(0, 0, this.canvas.width, this.canvas.height);
this.context.restore();
} else {
- this.context.clearRect(0, 0, this.size.x, this.size.y);
+ this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
if (this.previousScene) {
diff --git a/packages/core/src/transitions/index.ts b/packages/core/src/transitions/index.ts
index efa0622c..e4d39287 100644
--- a/packages/core/src/transitions/index.ts
+++ b/packages/core/src/transitions/index.ts
@@ -6,3 +6,5 @@
export * from './slideTransition';
export * from './useTransition';
+export * from './zoomInTransition';
+export * from './zoomOutTransition';
diff --git a/packages/core/src/transitions/slideTransition.ts b/packages/core/src/transitions/slideTransition.ts
index 17f36b54..21b191d0 100644
--- a/packages/core/src/transitions/slideTransition.ts
+++ b/packages/core/src/transitions/slideTransition.ts
@@ -2,11 +2,18 @@ import {Direction, Vector2} from '../types';
import {useScene} from '../utils';
import {useTransition} from './useTransition';
import {all} from '../flow';
+import {ThreadGenerator} from '../threading';
+/**
+ * Perform a transition that slides the scene in a given direction.
+ *
+ * @param direction - The direction in which to slide.
+ * @param duration - The duration of the transition.
+ */
export function* slideTransition(
direction: Direction = Direction.Top,
duration = 0.6,
-) {
+): ThreadGenerator {
const size = useScene().getSize();
const position = size.getOriginOffset(direction).scale(2);
const previousPosition = Vector2.createSignal();
diff --git a/packages/core/src/transitions/zoomInTransition.ts b/packages/core/src/transitions/zoomInTransition.ts
new file mode 100644
index 00000000..cb5f847a
--- /dev/null
+++ b/packages/core/src/transitions/zoomInTransition.ts
@@ -0,0 +1,47 @@
+import {Rect, Vector2} from '../types';
+import {useScene} from '../utils';
+import {useTransition} from './useTransition';
+import {clampRemap, easeInOutCubic, linear} from '../tweening';
+import {createSignal} from '../signals';
+import {all} from '../flow';
+import {ThreadGenerator} from '../threading';
+
+/**
+ * Perform a transition that zooms in on a given area of the scene.
+ *
+ * @param area - The area on which to zoom in.
+ * @param duration - The duration of the transition.
+ */
+export function* zoomInTransition(area: Rect, duration = 0.6): ThreadGenerator {
+ const scale = useScene().getSize().div(area.size);
+
+ const currentPosition = Vector2.createSignal(area.position);
+ const currentScale = Vector2.createSignal(Vector2.one.div(scale));
+ const previousPosition = Vector2.createSignal(0);
+ const previousScale = Vector2.createSignal(1);
+ const alpha = createSignal(0);
+
+ const endTransition = useTransition(
+ ctx => {
+ ctx.globalAlpha = clampRemap(0.1, 0.5, 0, 1, alpha());
+ ctx.translate(currentPosition.x(), currentPosition.y());
+ ctx.scale(currentScale.x(), currentScale.y());
+ },
+ ctx => {
+ ctx.globalAlpha = clampRemap(0.5, 0.9, 1, 0, alpha());
+ ctx.translate(previousPosition.x(), previousPosition.y());
+ ctx.scale(previousScale.x(), previousScale.y());
+ },
+ );
+
+ const timing = (v: number) => easeInOutCubic(v * v);
+ yield* all(
+ currentPosition(Vector2.zero, duration, timing),
+ previousPosition(area.position.flipped.mul(scale), duration, timing),
+ currentScale(1, duration, timing),
+ previousScale(scale, duration, timing),
+ alpha(1, duration, linear),
+ );
+
+ endTransition();
+}
diff --git a/packages/core/src/transitions/zoomOutTransition.ts b/packages/core/src/transitions/zoomOutTransition.ts
new file mode 100644
index 00000000..450ee38b
--- /dev/null
+++ b/packages/core/src/transitions/zoomOutTransition.ts
@@ -0,0 +1,52 @@
+import {Rect, Vector2} from '../types';
+import {useScene} from '../utils';
+import {useTransition} from './useTransition';
+import {clampRemap, easeInOutCubic, linear} from '../tweening';
+import {createSignal} from '../signals';
+import {all} from '../flow';
+import {ThreadGenerator} from '../threading';
+
+/**
+ * Perform a transition that zooms out from a given area of the scene.
+ *
+ * @param area - The area from which to zoom out.
+ * @param duration - The duration of the transition.
+ */
+export function* zoomOutTransition(
+ area: Rect,
+ duration = 0.6,
+): ThreadGenerator {
+ const scale = useScene().getSize().div(area.size);
+
+ const currentPosition = Vector2.createSignal(
+ area.position.flipped.mul(scale),
+ );
+ const currentScale = Vector2.createSignal(scale);
+ const previousPosition = Vector2.createSignal(0);
+ const previousScale = Vector2.createSignal(1);
+ const alpha = createSignal(0);
+
+ const endTransition = useTransition(
+ ctx => {
+ ctx.globalAlpha = clampRemap(0.1, 0.5, 0, 1, alpha());
+ ctx.translate(currentPosition.x(), currentPosition.y());
+ ctx.scale(currentScale.x(), currentScale.y());
+ },
+ ctx => {
+ ctx.globalAlpha = clampRemap(0.5, 0.9, 1, 0, alpha());
+ ctx.translate(previousPosition.x(), previousPosition.y());
+ ctx.scale(previousScale.x(), previousScale.y());
+ },
+ );
+
+ const timing = (v: number) => easeInOutCubic(Math.sqrt(v));
+ yield* all(
+ currentPosition(Vector2.zero, duration, timing),
+ previousPosition(area.position, duration, timing),
+ currentScale(1, duration, timing),
+ previousScale(Vector2.one.div(scale), duration, timing),
+ alpha(1, duration, linear),
+ );
+
+ endTransition();
+}
diff --git a/packages/core/src/utils/useScene.ts b/packages/core/src/utils/useScene.ts
index e3bae8c5..e441dd15 100644
--- a/packages/core/src/utils/useScene.ts
+++ b/packages/core/src/utils/useScene.ts
@@ -22,3 +22,14 @@ export function endScene(scene: Scene) {
throw new Error('startScene/endScene was called out of order.');
}
}
+
+/**
+ * Mark the current scene as ready to transition out.
+ *
+ * @remarks
+ * Usually used together with transitions. When a scene is marked as finished,
+ * the transition will start but the scene generator will continue running.
+ */
+export function finishScene() {
+ useScene().enterCanTransitionOut();
+}
diff --git a/packages/docs/docs/getting-started/layouts.mdx b/packages/docs/docs/getting-started/layouts.mdx
new file mode 100644
index 00000000..8d7e6dff
--- /dev/null
+++ b/packages/docs/docs/getting-started/layouts.mdx
@@ -0,0 +1,131 @@
+---
+sidebar_position: 5
+slug: /layouts
+---
+
+import AnimationPlayer from '@site/src/components/AnimationPlayer';
+import ApiSnippet from '@site/src/components/Api/ApiSnippet';
+
+# Layouts
+
+<AnimationPlayer name="layout" banner />
+
+Layouts allow you to arrange your nodes using [Flexbox][flexbox]. Any node
+extending the [`Layout`](/api/2d/components/Layout) node can become a part of
+the layout. This includes, but is not limited to:
+[`Rect`](/api/2d/components/Rect), [`Circle`](/api/2d/components/Circle), and
+[`Image`](/api/2d/components/Image).
+
+## Layout root
+
+Layouts are an opt-in feature, meaning that they need to be enabled. It's done
+by setting the [`layout`](/api/2d/components/Layout#layout) property on the Node
+that we want to become the root of our layout:
+
+```tsx
+// ↓ layout root
+<Rect layout>
+ {/* ↓ layout child */}
+ <Circle width={320} height={320} />
+</Rect>
+```
+
+In the example above, we marked the `<Rect>` as the layout root. This will cause
+the position and size of its descendants to be controlled by Flexbox (In this
+case there's only one valid descendant: `<Circle>`). The layout root itself is
+treated differently than its children - its size is controlled by Flexbox, but
+the position stays unaffected.
+
+:::info
+
+Just setting the `layout` property doesn't always turn the node into a layout
+root. If the node is already a part of the layout, it will be treated like the
+rest of the descendants:
+
+```tsx
+// ↓ layout root
+<Rect layout>
+ {/* ↓ layout child, NOT a layout root */}
+ <Rect layout>
+ {/* ↓ layout child */}
+ <Circle width={320} height={320} />
+ </Rect>
+</Rect>
+```
+
+:::
+
+## Size and offset
+
+Aside from the position, rotation, and scale, any node extending the `Layout`
+class has additional `size` and `offset` properties:
+
+### `Layout.size`
+
+<ApiSnippet url={'/api/2d/components/Layout#size'} />
+<hr />
+
+### `Layout.offset`
+
+<ApiSnippet url={'/api/2d/components/Layout#offset'} />
+<hr />
+
+## Flexbox configuration
+
+Most flexbox attributes available in CSS are available as
+[`Layout` properties](/api/2d/components/Layout#Properties). You can check out
+this [Flexbox guide][flexbox] to better understand how they work. The most
+useful properties are listed below:
+
+### `Layout.padding`
+
+<ApiSnippet url={'/api/2d/components/Layout#padding'} />
+<hr />
+
+### `Layout.margin`
+
+<ApiSnippet url={'/api/2d/components/Layout#margin'} />
+<hr />
+
+### `Layout.gap`
+
+<ApiSnippet url={'/api/2d/components/Layout#gap'} />
+<hr />
+
+### `Layout.direction`
+
+<ApiSnippet url={'/api/2d/components/Layout#direction'} />
+<hr />
+
+### `Layout.alignItems`
+
+<ApiSnippet url={'/api/2d/components/Layout#alignItems'} />
+<hr />
+
+### `Layout.justifyContent`
+
+<ApiSnippet url={'/api/2d/components/Layout#justifyContent'} />
+<hr />
+
+## Groups
+
+Nodes that don't extend the `Layout` class, such as the `Node` itself, are
+unaffected by the layout and are treated as if they were never there. This lets
+you apply filters and transformations to layout nodes without affecting the
+hierarchy.
+
+From the layout's perspective, all `<Rect>`s in the example below are siblings:
+
+```tsx
+<Layout direction={'column'} width={960} gap={40} layout>
+ <Node opacity={0.1}>
+ <Rect height={240} fill={'#ff6470'} />
+ <Rect height={240} fill={'#ff6470'} />
+ </Node>
+ <Rect height={240} fill={'#ff6470'} />
+</Layout>
+```
+
+<AnimationPlayer name="layout-group" small />
+
+[flexbox]: https://css-tricks.com/snippets/css/a-guide-to-flexbox/
diff --git a/packages/docs/docs/getting-started/positioning.mdx b/packages/docs/docs/getting-started/positioning.mdx
index efd4883c..26da999d 100644
--- a/packages/docs/docs/getting-started/positioning.mdx
+++ b/packages/docs/docs/getting-started/positioning.mdx
@@ -35,7 +35,7 @@ transform of each node consists of the following properties:
<ApiSnippet url={'/api/2d/components/Node#rotation'} />
<hr />
-## Absolute Transform
+## Absolute transform
Each of the basic transform properties has a dedicated helper method that
operates in world space.
diff --git a/packages/docs/docs/getting-started/rendering.mdx b/packages/docs/docs/getting-started/rendering.mdx
index 2b1026ef..3206e6fb 100644
--- a/packages/docs/docs/getting-started/rendering.mdx
+++ b/packages/docs/docs/getting-started/rendering.mdx
@@ -86,5 +86,6 @@ of your choice, or convert the frames directly to a video using a tool like
## Taking Snapshots
-You can use the <PhotoCamera className="icon-inline"/> icon take a snapshot of
-the current frame. Snapshots are saved in the output directory, under `/still`.
+You can use the <PhotoCamera className="icon-inline"/> icon to take a snapshot
+of the current frame. Snapshots are saved in the output directory, under
+`/still`.
diff --git a/packages/docs/docs/getting-started/time-events.mdx b/packages/docs/docs/getting-started/time-events.mdx
index 84dce356..8c049005 100644
--- a/packages/docs/docs/getting-started/time-events.mdx
+++ b/packages/docs/docs/getting-started/time-events.mdx
@@ -3,4 +3,48 @@ sidebar_position: 8
slug: /time-events
---
+import UI from '@site/src/components/UI';
+
# Time Events
+
+One of the pain points of creating explanatory animations using code is
+**synchronizing them with audio**. Imagine that you'd like a certain animation
+to start right after some specific verbal cue. With a code-only solution, you're
+left with hard-coding how long (or until which frame) you want to wait.
+
+In Motion Canvas, it could look somewhat like this:
+
+```ts
+yield * animationOne();
+yield * waitFor(3.1415); // but how long should we wait?
+yield * animationTwo();
+```
+
+Evidently, this approach can get really tedious. Not only do you need to somehow
+find the exact timestamp to wait for, but also each time you modify the
+voiceover, you have to go through your code and adjust these hard-coded numbers.
+
+That's why Motion Canvas allows you to edit these delays not through code, but
+through the editor. With the use of [`waitUntil`](/api/core/flow#waitUntil) you
+can pause the animation without specifying the actual duration:
+
+```ts
+yield * animationOne();
+yield * waitUntil('event'); // wait for an event called "event"
+yield * animationTwo();
+```
+
+This will cause the event to appear in the editor. From there, you can drag it
+to adjust its timing:
+
+<UI className="image-inline" />
+
+The dark trail behind the event illustrates its duration. It starts at the
+moment `waitUntil` was called - this is when the animation will pause. It will
+resume when the playhead reaches the event pill.
+
+By default, adjusting a time event will also adjust all events that happen after
+it. This is useful when you want to extend or shorten a pause in your voiceover
+because correcting the first time event after the pause will also fix all events
+after it. You can hold `SHIFT` when editing an event to prevent this from
+happening.
diff --git a/packages/docs/docs/getting-started/transitions.mdx b/packages/docs/docs/getting-started/transitions.mdx
index 5bac7e56..92669caa 100644
--- a/packages/docs/docs/getting-started/transitions.mdx
+++ b/packages/docs/docs/getting-started/transitions.mdx
@@ -3,4 +3,117 @@ sidebar_position: 9
slug: /transitions
---
+import ApiSnippet from '@site/src/components/Api/ApiSnippet';
+
# Transitions
+
+Transitions allow you to customize the way scenes transition from one into
+another. A transition is an animation performed at the beginning of the scene.
+It can modify the context of both the current and the previous scene.
+
+## Pre-made transitions
+
+Motion Canvas comes with a set of common transitions in a form of easy-to-use
+generator. To use them, yield the transition generator at the beggining of the
+scene:
+
+```ts
+export default makeScene2D(function* (view) {
+ // perform a slide transition to the left:
+ yield* slideTransition(Direction.Left);
+ // proceed with the animation
+});
+```
+
+The available transitions are:
+
+### `slideTransition`
+
+<ApiSnippet url={'/api/core/transitions#slideTransition'} />
+<hr />
+
+### `zoomInTransition`
+
+<ApiSnippet url={'/api/core/transitions#zoomInTransition'} />
+<hr />
+
+### `zoomOutTransition`
+
+<ApiSnippet url={'/api/core/transitions#zoomOutTransition'} />
+<hr />
+
+## Custom transitions
+
+You can use the [`useTransition`](/api/core/transitions#useTransition) function
+to implement custom transitions. It allows you to specify two callbacks that
+will modify the contexts of the current and previous scene respectively. The
+value it returns is a callback that you need to call once you finish the
+transition.
+
+The transition template looks as follows:
+
+```ts
+// set up the transition
+const endTransition = useTransition(
+ currentContext => {
+ // modify the context of the current scene
+ },
+ previousContext => {
+ // modify the context of the previous scene
+ },
+);
+
+// perform animations
+
+// finish the transition
+endTransition();
+```
+
+Here's how you could implement a simple slide transition:
+
+```ts
+export function* slideTransition(
+ direction: Direction = Direction.Top,
+ duration = 0.6,
+): ThreadGenerator {
+ const size = useScene().getSize();
+ const position = size.getOriginOffset(direction).scale(2);
+ const previousPosition = Vector2.createSignal();
+ const currentPosition = Vector2.createSignal(position);
+
+ // set up the transition
+ const endTransition = useTransition(
+ // modify the context of the current scene
+ ctx => ctx.translate(currentPosition.x(), currentPosition.y()),
+ // modify the context of the previous scene
+ ctx => ctx.translate(previousPosition.x(), previousPosition.y()),
+ );
+
+ // perform animations
+ yield* all(
+ previousPosition(position.scale(-1), duration),
+ currentPosition(Vector2.zero, duration),
+ );
+
+ // finish the transition
+ endTransition();
+}
+```
+
+## Animate when transitioning
+
+By default, Motion Canvas will transition to the next scene once the generator
+of the current scene has reached the end. In this case, the scene will freeze
+for the duration of the transition. You can use the
+[`finishScene`](/api/core/utils#finishScene) function to trigger the transition
+early, allowing the animation to continue while transitioning:
+
+```tsx
+export default makeScene2D(function* (view) {
+ yield* animationOne();
+ // trigger the transition early:
+ finishScene();
+ // continue animating:
+ yield* animationTwo();
+});
+```
diff --git a/packages/docs/docs/intro.md b/packages/docs/docs/intro.md
index cd68da7e..e682415f 100644
--- a/packages/docs/docs/intro.md
+++ b/packages/docs/docs/intro.md
@@ -5,34 +5,23 @@ slug: /
# Introduction
-Motion Canvas is a TypeScript library and web application for creating
-animations programmatically. It was invented to accelerate the process of
-combining informative voice overs with supporting animation, but can satisfy a
-variety of use cases. Animations are programmed in either TypeScript or
-JavaScript using the Motion Canvas core library. The Motion Canvas web app then
-displays a preview of the animations with an audio file of your choice.
+Motion Canvas consists of two main components:
-Though most details of the animation are driven by code, your program may
-selectively defer the timing of some events to be edited in the web app using a
-function called `waitUntil`. From the web app, you may then drag and drop this
-timing event to fine tune your animations. This is most useful for synchronizing
-the timing of animations with your voice over. This way, you may program the
-precise details of your animation in code, but adjust them manually to match the
-imprecise timing of a recorded voice over.
+- A TypeScript library used to program animations.
+- An editor providing a real-time preview of said animations.
-Motion Canvas is not intended to be a full-sale replacement for a video editor
-like Adobe Premiere Pro or DaVinci Resolve, but it may improve your workflow
-when combined with these other tools.
+It's a specialized tool designed to create informative vector animations and
+synchronize them with voice-overs. It's not meant to be a replacement for
+traditional video editing software.
-Motion Canvas is Open Source, and relies on your feedback to inform its
-development. If you would like to report a bug or request a feature, you may
-visit [the GitHub repository][repo] to do so. We cannot satisfy every request,
-but we do read every request, and are dedicated to making Motion Canvas work for
-as wide a user base as possible.
+Aside from providing a preview, the editor allows you to edit certain aspects of
+the animation that could otherwise be tedious. You can learn more about this
+functionality in the [time events](/docs/time-events) section.
-If you would like to contribute pull requests, please read [the contribution
-guide][contributing] to learn about our process.
+Motion Canvas is a free and open source project. You can help making it better
+by reporting bugs, requesting features, or contributing to the codebase. If
+you're interested, our [contribution guide][contributing] will help you get
+started.
[contributing]:
https://github.com/motion-canvas/motion-canvas/blob/main/CONTRIBUTING.md
-[repo]: https://github.com/motion-canvas/motion-canvas
diff --git a/packages/docs/docusaurus.config.js b/packages/docs/docusaurus.config.js
index adaa0384..87e6294e 100644
--- a/packages/docs/docusaurus.config.js
+++ b/packages/docs/docusaurus.config.js
@@ -118,7 +118,7 @@ const config = {
showLastUpdateAuthor: true,
docItemComponent: '@site/src/components/DocPage',
editUrl: ({versionDocsDirPath, docPath}) =>
- `https://github.com/motion-canvas/motion-canvas/blob/main/${versionDocsDirPath}/${docPath}`,
+ `https://github.com/motion-canvas/motion-canvas/blob/main/packages/docs/${versionDocsDirPath}/${docPath}`,
},
],
[
@@ -126,7 +126,7 @@ const config = {
{
showReadingTime: true,
editUrl: ({blogDirPath, blogPath}) =>
- `https://github.com/motion-canvas/motion-canvas/blob/main/${blogDirPath}/${blogPath}`,
+ `https://github.com/motion-canvas/motion-canvas/blob/main/packages/docs/${blogDirPath}/${blogPath}`,
},
],
'@docusaurus/plugin-content-pages',
diff --git a/packages/docs/src/components/Api/ApiSnippet.tsx b/packages/docs/src/components/Api/ApiSnippet.tsx
index e7214aad..24891764 100644
--- a/packages/docs/src/components/Api/ApiSnippet.tsx
+++ b/packages/docs/src/components/Api/ApiSnippet.tsx
@@ -1,16 +1,8 @@
import React from 'react';
import {useUrlLookup} from '@site/src/contexts/api';
import Item from '@site/src/components/Api/Item';
-import Link from '@docusaurus/Link';
export default function ApiSnippet({url}: {url: string}) {
const reflection = useUrlLookup()(url);
- return (
- <>
- <Item reflection={reflection} headless />
- <Link to={reflection.href}>
- <small>Got to the API documentation</small>
- </Link>
- </>
- );
+ return <Item reflection={reflection} headless />;
}
diff --git a/packages/docs/src/components/Homepage/Features.tsx b/packages/docs/src/components/Homepage/Features.tsx
index 71e81707..2280b3b3 100644
--- a/packages/docs/src/components/Homepage/Features.tsx
+++ b/packages/docs/src/components/Homepage/Features.tsx
@@ -98,7 +98,7 @@ export default function HomepageFeatures(): JSX.Element {
</Feature>
<Feature
content={
- <YouTubeVideo src="https://www.youtube.com/embed/HsOKwUwL1bE" />
+ <YouTubeVideo src="https://www.youtube.com/embed/R6vQ9VmMz2w" />
}
>
<h3>
@@ -108,6 +108,15 @@ export default function HomepageFeatures(): JSX.Element {
The road ahead is still long, but you can already use Motion Canvas
to create production-quality animations.
</p>
+ <p>
+ <a
+ className="button button--outline button--lg"
+ href="https://github.com/motion-canvas/examples"
+ target="_blank"
+ >
+ Video Source Code
+ </a>
+ </p>
</Feature>
</div>
</section>
diff --git a/packages/docs/src/components/UI/index.tsx b/packages/docs/src/components/UI/index.tsx
new file mode 100644
index 00000000..33c939cc
--- /dev/null
+++ b/packages/docs/src/components/UI/index.tsx
@@ -0,0 +1,7 @@
+import React from 'react';
+import Svg from '@site/static/img/ui.svg';
+import styles from './styles.module.css';
+
+export default function UI() {
+ return <Svg className={styles.root} />;
+}
diff --git a/packages/docs/src/components/UI/styles.module.css b/packages/docs/src/components/UI/styles.module.css
new file mode 100644
index 00000000..92cba0a1
--- /dev/null
+++ b/packages/docs/src/components/UI/styles.module.css
@@ -0,0 +1,24 @@
+.root {
+ display: block;
+ max-width: 640px;
+ margin: 0 auto var(--ifm-leading);
+ background-color: var(--ifm-background-surface-color);
+ border-radius: var(--ifm-global-radius);
+ border: 1px solid var(--ifm-color-emphasis-100);
+}
+
+.root g {
+ animation: slide 4s infinite;
+}
+
+@keyframes slide {
+ 0% {
+ transform: translateX(0px);
+ }
+ 50% {
+ transform: translateX(-100px);
+ }
+ 100% {
+ transform: translateX(0px);
+ }
+}
diff --git a/packages/examples/src/layout-group.meta b/packages/examples/src/layout-group.meta
new file mode 100644
index 00000000..0e33e3fe
--- /dev/null
+++ b/packages/examples/src/layout-group.meta
@@ -0,0 +1,3 @@
+{
+ "version": 0
+}
\ No newline at end of file
diff --git a/packages/examples/src/layout-group.ts b/packages/examples/src/layout-group.ts
new file mode 100644
index 00000000..a3f937ee
--- /dev/null
+++ b/packages/examples/src/layout-group.ts
@@ -0,0 +1,7 @@
+import {makeProject} from '@motion-canvas/core';
+
+import scene from './scenes/layout-group?scene';
+
+export default makeProject({
+ scenes: [scene],
+});
diff --git a/packages/examples/src/scenes/layout-group.meta b/packages/examples/src/scenes/layout-group.meta
new file mode 100644
index 00000000..44ec0647
--- /dev/null
+++ b/packages/examples/src/scenes/layout-group.meta
@@ -0,0 +1,4 @@
+{
+ "version": 1,
+ "seed": 2413678884
+}
\ No newline at end of file
diff --git a/packages/examples/src/scenes/layout-group.tsx b/packages/examples/src/scenes/layout-group.tsx
new file mode 100644
index 00000000..1c7ec3ff
--- /dev/null
+++ b/packages/examples/src/scenes/layout-group.tsx
@@ -0,0 +1,21 @@
+import {makeScene2D} from '@motion-canvas/2d/lib/scenes';
+import {Node, Rect, Layout} from '@motion-canvas/2d/lib/components';
+import {createRef} from '@motion-canvas/core/lib/utils';
+
+export default makeScene2D(function* (view) {
+ const group = createRef<Node>();
+
+ view.add(
+ <>
+ <Layout direction={'column'} width={960} gap={40} layout>
+ <Node ref={group}>
+ <Rect height={240} fill={'#ff6470'} />
+ <Rect height={240} fill={'#ff6470'} />
+ </Node>
+ <Rect height={240} fill={'#ff6470'} />
+ </Layout>
+ </>,
+ );
+
+ yield* group().opacity(0.1, 1).to(1, 1);
+});
diff --git a/packages/examples/vite.config.ts b/packages/examples/vite.config.ts
index ca0651c0..4fcf3b0c 100644
--- a/packages/examples/vite.config.ts
+++ b/packages/examples/vite.config.ts
@@ -13,6 +13,7 @@ export default defineConfig({
'./src/node-signal.ts',
'./src/random.ts',
'./src/layout.ts',
+ './src/layout-group.ts',
'./src/positioning.ts',
],
}),