Skip to content

Visualize Your Ideas With Code

feat(2d): add Bézier nodes (#603)

Kai Sassnowski9841cfdc3947
diff --git a/packages/2d/src/components/Bezier.ts b/packages/2d/src/components/Bezier.ts
new file mode 100644
index 00000000..5140f116
--- /dev/null
+++ b/packages/2d/src/components/Bezier.ts
@@ -0,0 +1,108 @@
+import {BBox, SerializedVector2, Vector2} from '@motion-canvas/core/lib/types';
+import {Curve} from './Curve';
+import {CurveProfile} from '../curves';
+import {PolynomialSegment} from '../curves/PolynomialSegment';
+import {DesiredLength} from '../partials';
+import {arc, drawLine, lineTo, moveTo} from '../utils';
+import {computed} from '../decorators';
+
+export interface BezierOverlayInfo {
+ curve: Path2D;
+ handleLines: Path2D;
+ controlPoints: Vector2[];
+ startPoint: Vector2;
+ endPoint: Vector2;
+}
+
+export abstract class Bezier extends Curve {
+ public override profile(): CurveProfile {
+ const segment = this.segment();
+ return {
+ segments: [segment],
+ arcLength: segment.arcLength,
+ minSin: 0,
+ };
+ }
+
+ protected abstract segment(): PolynomialSegment;
+
+ protected abstract overlayInfo(matrix: DOMMatrix): BezierOverlayInfo;
+
+ @computed()
+ protected childrenBBox(): BBox {
+ return BBox.fromPoints(...this.segment().points);
+ }
+
+ protected override desiredSize(): SerializedVector2<DesiredLength> {
+ return this.segment().getBBox().size;
+ }
+
+ protected override offsetComputedLayout(box: BBox): BBox {
+ box.position = box.position.sub(this.segment().getBBox().center);
+ return box;
+ }
+
+ public override drawOverlay(
+ context: CanvasRenderingContext2D,
+ matrix: DOMMatrix,
+ ) {
+ const size = this.computedSize();
+ const box = this.childrenBBox().transformCorners(matrix);
+ const offset = size.mul(this.offset()).scale(0.5).transformAsPoint(matrix);
+ const overlayInfo = this.overlayInfo(matrix);
+
+ context.lineWidth = 1;
+ context.strokeStyle = 'white';
+ context.fillStyle = 'white';
+
+ // Draw the curve itself first so everything else gets drawn on top of it
+ context.stroke(overlayInfo.curve);
+
+ context.fillStyle = 'white';
+ context.globalAlpha = 0.5;
+
+ context.beginPath();
+ context.stroke(overlayInfo.handleLines);
+
+ context.globalAlpha = 1;
+ context.lineWidth = 2;
+
+ // Draw start and end points
+ for (const point of [overlayInfo.startPoint, overlayInfo.endPoint]) {
+ moveTo(context, point);
+ context.beginPath();
+ arc(context, point, 4);
+ context.closePath();
+ context.stroke();
+ context.fill();
+ }
+
+ // Draw the control points
+ context.fillStyle = 'black';
+ for (const point of overlayInfo.controlPoints) {
+ moveTo(context, point);
+ context.beginPath();
+ arc(context, point, 4);
+ context.closePath();
+ context.fill();
+ context.stroke();
+ }
+
+ // Draw the offset marker
+ context.lineWidth = 1;
+ const radius = 8;
+ context.beginPath();
+ lineTo(context, offset.addY(-radius));
+ lineTo(context, offset.addY(radius));
+ lineTo(context, offset);
+ lineTo(context, offset.addX(-radius));
+ context.arc(offset.x, offset.y, radius, 0, Math.PI * 2);
+ context.stroke();
+
+ // Draw the bounding box
+ context.beginPath();
+ drawLine(context, box);
+ context.closePath();
+ context.stroke();
+ }
+}
diff --git a/packages/2d/src/components/CubicBezier.ts b/packages/2d/src/components/CubicBezier.ts
new file mode 100644
index 00000000..29b63994
--- /dev/null
+++ b/packages/2d/src/components/CubicBezier.ts
@@ -0,0 +1,108 @@
+import {SignalValue} from '@motion-canvas/core/lib/signals';
+import {PossibleVector2, Vector2Signal} from '@motion-canvas/core/lib/types';
+import {CurveProps} from './Curve';
+import {CubicBezierSegment} from '../curves';
+import {PolynomialSegment} from '../curves/PolynomialSegment';
+import {computed, vector2Signal} from '../decorators';
+import {bezierCurveTo, lineTo, moveTo} from '../utils';
+import {Bezier, BezierOverlayInfo} from './Bezier';
+
+export interface CubicBezierProps extends CurveProps {
+ p0: SignalValue<PossibleVector2>;
+ p0X: SignalValue<number>;
+ p0Y: SignalValue<number>;
+
+ p1: SignalValue<PossibleVector2>;
+ p1X: SignalValue<number>;
+ p1Y: SignalValue<number>;
+
+ p2: SignalValue<PossibleVector2>;
+ p2X: SignalValue<number>;
+ p2Y: SignalValue<number>;
+
+ p3: SignalValue<PossibleVector2>;
+ p3X: SignalValue<number>;
+ p3Y: SignalValue<number>;
+}
+
+/**
+ * A node for drawing a cubic Bézier curve.
+ *
+ * @preview
+ * Defining a cubic Bézier curve using `points` property.
+ *
+ * ```tsx editor
+ * export default makeScene2D(function* (view) {
+ * const bezier = createRef<CubicBezier>();
+ *
+ * <CubicBezier
+ * lineWidth={4}
+ * stroke={'lightseagreen'}
+ * p0={[-200, -200]}
+ * p1={[100, -200]}
+ * p2={[-100, 200]}
+ * p3={[200, 200]}
+ * end={0}
+ * />
+ *
+ * yield* bezier().end(1, 1);
+ * yield* bezier().start(1, 1).to(0, 1);
+ * });
+ * ```
+ */
+export class CubicBezier extends Bezier {
+ /**
+ * The start point of the Bézier curve.
+ */
+ @vector2Signal('p0')
+ public declare readonly p0: Vector2Signal<this>;
+
+ /**
+ * The first control point of the Bézier curve.
+ */
+ @vector2Signal('p1')
+ public declare readonly p1: Vector2Signal<this>;
+
+ /**
+ * The second control point of the Bézier curve.
+ */
+ @vector2Signal('p2')
+ public declare readonly p2: Vector2Signal<this>;
+
+ /**
+ * The end point of the Bézier curve.
+ */
+ @vector2Signal('p3')
+ public declare readonly p3: Vector2Signal<this>;
+
+ public constructor(props: CubicBezierProps) {
+ super(props);
+ }
+
+ @computed()
+ protected segment(): PolynomialSegment {
+ return new CubicBezierSegment(this.p0(), this.p1(), this.p2(), this.p3());
+ }
+
+ protected overlayInfo(matrix: DOMMatrix): BezierOverlayInfo {
+ const [p0, p1, p2, p3] = this.segment().transformPoints(matrix);
+
+ const curvePath = new Path2D();
+ moveTo(curvePath, p0);
+ bezierCurveTo(curvePath, p1, p2, p3);
+
+ const handleLinesPath = new Path2D();
+ moveTo(handleLinesPath, p0);
+ lineTo(handleLinesPath, p1);
+ moveTo(handleLinesPath, p2);
+ lineTo(handleLinesPath, p3);
+
+ return {
+ curve: curvePath,
+ startPoint: p0,
+ endPoint: p3,
+ controlPoints: [p1, p2],
+ handleLines: handleLinesPath,
+ };
+ }
+}
diff --git a/packages/2d/src/components/QuadBezier.ts b/packages/2d/src/components/QuadBezier.ts
new file mode 100644
index 00000000..c70a65bd
--- /dev/null
+++ b/packages/2d/src/components/QuadBezier.ts
@@ -0,0 +1,97 @@
+import {SignalValue} from '@motion-canvas/core/lib/signals';
+import {PossibleVector2, Vector2Signal} from '@motion-canvas/core/lib/types';
+import {QuadBezierSegment} from '../curves';
+import {PolynomialSegment} from '../curves/PolynomialSegment';
+import {computed, vector2Signal} from '../decorators';
+import {lineTo, moveTo, quadraticCurveTo} from '../utils';
+import {Bezier, BezierOverlayInfo} from './Bezier';
+import {CurveProps} from './Curve';
+
+export interface QuadBezierProps extends CurveProps {
+ p0: SignalValue<PossibleVector2>;
+ p0X: SignalValue<number>;
+ p0Y: SignalValue<number>;
+
+ p1: SignalValue<PossibleVector2>;
+ p1X: SignalValue<number>;
+ p1Y: SignalValue<number>;
+
+ p2: SignalValue<PossibleVector2>;
+ p2X: SignalValue<number>;
+ p2Y: SignalValue<number>;
+}
+
+/**
+ * A node for drawing a quadratic Bézier curve.
+ *
+ * @preview
+ * ```tsx editor
+ * export default makeScene2D(function* (view) {
+ * const bezier = createRef<QuadBezier>();
+ *
+ * view.add(
+ * <QuadBezier
+ * ref={bezier}
+ * lineWidth={4}
+ * stroke={'lightseagreen'}
+ * p0={[-200, 0]}
+ * p1={[0, -200]}
+ * p2={[200, 0]}
+ * end={0}
+ * />
+ * );
+ *
+ * yield* bezier().end(1, 1);
+ * yield* bezier().start(1, 1).to(0, 1);
+ * });
+ * ```
+ */
+export class QuadBezier extends Bezier {
+ /**
+ * The start point of the Bézier curve.
+ */
+ @vector2Signal('p0')
+ public declare readonly p0: Vector2Signal<this>;
+
+ /**
+ * The control point of the Bézier curve.
+ */
+ @vector2Signal('p1')
+ public declare readonly p1: Vector2Signal<this>;
+
+ /**
+ * The end point of the Bézier curve.
+ */
+ @vector2Signal('p2')
+ public declare readonly p2: Vector2Signal<this>;
+
+ public constructor(props: QuadBezierProps) {
+ super(props);
+ }
+
+ @computed()
+ protected segment(): PolynomialSegment {
+ return new QuadBezierSegment(this.p0(), this.p1(), this.p2());
+ }
+
+ protected overlayInfo(matrix: DOMMatrix): BezierOverlayInfo {
+ const [p0, p1, p2] = this.segment().transformPoints(matrix);
+
+ const curvePath = new Path2D();
+ moveTo(curvePath, p0);
+ quadraticCurveTo(curvePath, p1, p2);
+
+ const handleLinesPath = new Path2D();
+ moveTo(handleLinesPath, p0);
+ lineTo(handleLinesPath, p1);
+ lineTo(handleLinesPath, p2);
+
+ return {
+ curve: curvePath,
+ startPoint: p0,
+ endPoint: p2,
+ controlPoints: [p1],
+ handleLines: handleLinesPath,
+ };
+ }
+}
diff --git a/packages/2d/src/components/index.ts b/packages/2d/src/components/index.ts
index 32579804..62e01cba 100644
--- a/packages/2d/src/components/index.ts
+++ b/packages/2d/src/components/index.ts
@@ -1,4 +1,5 @@
export * from './Circle';
+export * from './CubicBezier';
export * from './Icon';
export * from './Img';
export * from './Grid';
@@ -9,6 +10,7 @@ export * from './Line';
export * from './Node';
export * from './Rect';
export * from './Polygon';
+export * from './QuadBezier';
export * from './Shape';
export * from './Spline';
export * from './Txt';
diff --git a/packages/docs/docs/components/bezier.mdx b/packages/docs/docs/components/bezier.mdx
new file mode 100644
index 00000000..db19d64c
--- /dev/null
+++ b/packages/docs/docs/components/bezier.mdx
@@ -0,0 +1,285 @@
+---
+sidebar_position: 3
+slug: /bezier-curves
+---
+
+# Bézier Curves
+
+```tsx editor
+// snippet Cubic Bézier
+import {makeScene2D} from '@motion-canvas/2d/lib/scenes';
+import {CubicBezier} from '@motion-canvas/2d/lib/components';
+import {createRef} from '@motion-canvas/core/lib/utils';
+import {all} from '@motion-canvas/core/lib/flow';
+
+export default makeScene2D(function* (view) {
+ const bezier = createRef<Spline>();
+
+ view.add(
+ <CubicBezier
+ ref={bezier}
+ lineWidth={6}
+ stroke={'lightseagreen'}
+ p0={[-200, -70]}
+ p1={[120, -120]}
+ p2={[-120, 120]}
+ p3={[200, 70]}
+ end={0}
+ />,
+ );
+
+ yield* bezier().end(1, 1);
+ yield* bezier().start(1, 1).to(0, 1);
+});
+
+// snippet Quadratic Bézier
+import {makeScene2D} from '@motion-canvas/2d/lib/scenes';
+import {QuadBezier} from '@motion-canvas/2d/lib/components';
+import {createRef} from '@motion-canvas/core/lib/utils';
+import {all} from '@motion-canvas/core/lib/flow';
+
+export default makeScene2D(function* (view) {
+ const bezier = createRef<Spline>();
+
+ view.add(
+ <QuadBezier
+ ref={bezier}
+ lineWidth={6}
+ stroke={'lightseagreen'}
+ p0={[-150, 50]}
+ p1={[0, -120]}
+ p2={[150, 50]}
+ end={0}
+ />,
+ );
+
+ yield* bezier().end(1, 1);
+ yield* bezier().start(1, 1).to(0, 1);
+});
+```
+
+Bézier curves are ubiquitous in computer graphics. Motion Canvas comes with
+components to draw both quadratic and cubic Bézier curves.
+
+:::tip
+
+If you're trying to draw more complicated shapes than single Bézier curves allow
+for, check out the [`Spline`][spline] component, instead.
+
+:::
+
+## Using the components
+
+Each example below applies to both the [`QuadBezier`][quad-bezier] and
+[`CubicBezier`][cubic-bezier] nodes. You can switch between the two types of
+curves using the dropdown on the right side of the animation player.
+
+### Defining control points
+
+Bézier curves are defined by a start and end point, as well as several control
+points. The exact number of control points is different for different kinds of
+Bézier curves. A quadratic Bézier curve has only a single control point whereas
+a cubic Bézier curve has two.
+
+```tsx editor
+// snippet Cubic Bézier
+export default makeScene2D(function* (view) {
+ const bezier = createRef<CubicBezier>();
+
+ view.add(
+ <CubicBezier
+ ref={bezier}
+ lineWidth={6}
+ stroke={'lightseagreen'}
+ p0={[-200, -70]}
+ p1={[120, -120]}
+ p2={[-120, 120]}
+ p3={[200, 70]}
+ />,
+ );
+
+ yield* waitFor(1);
+});
+
+// snippet Quadratic Bézier
+export default makeScene2D(function* (view) {
+ const bezier = createRef<QuadBezier>();
+
+ view.add(
+ <QuadBezier
+ ref={bezier}
+ lineWidth={6}
+ stroke={'lightseagreen'}
+ p0={[-150, 50]}
+ p1={[0, -120]}
+ p2={[150, 50]}
+ />,
+ );
+
+ yield* waitFor(1);
+});
+```
+
+All points of a Bézier curve are compound signals. This means that it's possible
+to animate their `x` and `y` components separately.
+
+```tsx {6,13}
+view.add(
+ <CubicBezier
+ ref={bezier}
+ lineWidth={6}
+ stroke={'lightseagreen'}
+ p0={[-200, -70]}
+ p1={[120, -120]}
+ p2={[-120, 120]}
+ p3={[200, 70]}
+ />,
+);
+
+yield * bezier().p0.x(200, 1);
+```
+
+### Drawing arrows
+
+Similar to the [`Line`][line] and [`Spline`][spline] components, we can also add
+arrowheads to a Bézier curve. To do so, we can use the
+[`startArrow`][start-arrow] and [`endArrow`][end-arrow] properties. We can
+control the size of the arrowheads with the [`arrowSize`][arrow-size] signal.
+
+```tsx editor
+// snippet Cubic Bézier
+export default makeScene2D(function* (view) {
+ const bezier = createRef<CubicBezier>();
+
+ view.add(
+ <CubicBezier
+ ref={bezier}
+ lineWidth={6}
+ stroke={'lightseagreen'}
+ p0={[-200, -70]}
+ p1={[120, -120]}
+ p2={[-120, 120]}
+ p3={[200, 70]}
+ arrowSize={16}
+ startArrow
+ endArrow
+ />,
+ );
+
+ yield* bezier().arrowSize(20, 1).to(10, 1).to(16, 1);
+});
+
+// snippet Quadratic Bézier
+export default makeScene2D(function* (view) {
+ const bezier = createRef<QuadBezier>();
+
+ view.add(
+ <QuadBezier
+ ref={bezier}
+ lineWidth={6}
+ stroke={'lightseagreen'}
+ p0={[-150, 50]}
+ p1={[0, -120]}
+ p2={[150, 50]}
+ arrowSize={16}
+ startArrow
+ endArrow
+ />,
+ );
+
+ yield* bezier().arrowSize(20, 1).to(10, 1).to(16, 1);
+});
+```
+
+:::tip Animating adding arrows
+
+Since `startArrow` and `endArrow` are booleans, they don't lend themselves well
+to being animated. To animate adding arrows to a Bézier curve, we should animate
+`arrowSize`, instead.
+
+```tsx {7,13}
+view.add(
+ <QuadBezier
+ ref={bezier}
+ p0={[-150, 50]}
+ p1={[0, -120]}
+ p2={[150, 50]}
+ arrowSize={0}
+ startArrow
+ endArrow
+ />,
+);
+
+yield * bezier().arrowSize(16, 1);
+```
+
+:::
+
+## Examples
+
+The following section shows examples of common animations for Bézier curves.
+
+```tsx editor
+// snippet Drawing Bézier curves
+export default makeScene2D(function* (view) {
+ const bezier = createRef<CubicBezier>();
+
+ view.add(
+ <CubicBezier
+ ref={bezier}
+ lineWidth={6}
+ stroke={'lightseagreen'}
+ p0={[-200, -70]}
+ p1={[120, -120]}
+ p2={[-120, 120]}
+ p3={[200, 70]}
+ end={0}
+ />,
+ );
+
+ yield* bezier().end(1, 2).to(0, 2);
+});
+
+// snippet Moving nodes along a curve
+export default makeScene2D(function* (view) {
+ const bezier = createRef<CubicBezier>();
+
+ const progress = createSignal(0);
+ const curvePoint = createComputed(() =>
+ bezier().getPointAtPercentage(progress()),
+ );
+
+ view.add(
+ <>
+ <CubicBezier
+ ref={bezier}
+ lineWidth={6}
+ stroke={'lightgray'}
+ p0={[-300, -70]}
+ p1={[120, -120]}
+ p2={[-120, 120]}
+ p3={[300, 70]}
+ />
+ <Rect
+ size={25}
+ fill={'lightseagreen'}
+ position={() => curvePoint().position}
+ rotation={() => curvePoint().tangent.degrees}
+ />
+ </>,
+ );
+
+ yield* progress(1, 2);
+ yield* waitFor(0.5);
+ yield* progress(0, 2);
+ yield* waitFor(0.5);
+});
+```
+
+[spline]: /docs/spline
+[line]: /api/2d/components/Line
+[quad-bezier]: /api/2d/components/QuadBezier
+[cubic-bezier]: /api/2d/components/CubicBezier
+[start-arrow]: /api/2d/components/CurveProps#startArrow
+[end-arrow]: /api/2d/components/CurveProps#endArrow
+[arrow-size]: /api/2d/components/CurveProps#arrowSize
diff --git a/packages/docs/docs/components/custom-components.mdx b/packages/docs/docs/components/custom-components.mdx
index cf159a92..987874ca 100644
--- a/packages/docs/docs/components/custom-components.mdx
+++ b/packages/docs/docs/components/custom-components.mdx
@@ -1,5 +1,5 @@
---
-sidebar_position: 4
+sidebar_position: 5
slug: /custom-components
---
diff --git a/packages/docs/docs/components/spline.mdx b/packages/docs/docs/components/spline.mdx
index 7eca2290..182b5ea1 100644
--- a/packages/docs/docs/components/spline.mdx
+++ b/packages/docs/docs/components/spline.mdx
@@ -1,5 +1,5 @@
---
-sidebar_position: 3
+sidebar_position: 4
slug: /spline
---
@@ -34,6 +34,13 @@ export default makeScene2D(function* (view) {
The [`Spline`][spline] component allows us to draw and animate smooth curves
through a series of control points.
+:::tip
+
+If all you want to do is draw a simple Bézier curve, check out the [Bézier curve
+components][bezier-curves], instead.
+
+:::
+
## Defining control points
In order to draw a spline, we need to specify what its knots are. The `Spline`
@@ -452,6 +459,7 @@ The `getPointAtPercentage` method returns a [`CurvePoint`][curve-point] object
which contains the position of the point that sits at the given percentage along
the spline's arclength as well as the point's tangent vector.
+[bezier-curves]: /docs/bezier-curves
[spline]: /api/2d/components/Spline
[knot]: /api/2d/components/Knot
[line]: /api/2d/components/Line