Skip to content

Visualize Your Ideas With Code

feat(2d): add Path component (#700)

Levi Rizki Saputra2128b6bf871c
diff --git a/package-lock.json b/package-lock.json
index d7bc7f47..e6ef840b 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -8,9 +8,6 @@
"workspaces": [
"packages/*"
],
- "dependencies": {
- "@motion-canvas/core": "^3.0.0"
- },
"devDependencies": {
"@commitlint/cli": "^17.0.3",
"@commitlint/config-conventional": "^17.0.3",
@@ -17362,6 +17359,11 @@
"protocols": "^2.0.0"
}
},
+ "node_modules/parse-svg-path": {
+ "version": "0.1.2",
+ "resolved": "https://registry.npmjs.org/parse-svg-path/-/parse-svg-path-0.1.2.tgz",
+ "integrity": "sha512-JyPSBnkTJ0AI8GGJLfMXvKq42cj5c006fnLz6fXy6zfoVjJizi8BNTpu8on8ziI1cKy9d9DGNuY17Ce7wuejpQ=="
+ },
"node_modules/parse-url": {
"version": "8.1.0",
"resolved": "https://registry.npmjs.org/parse-url/-/parse-url-8.1.0.tgz",
@@ -22939,7 +22941,8 @@
"dependencies": {
"@motion-canvas/core": "^3.9.0",
"code-fns": "^0.8.2",
- "mathjax-full": "^3.2.2"
+ "mathjax-full": "^3.2.2",
+ "parse-svg-path": "^0.1.2"
},
"devDependencies": {
"@motion-canvas/internal": "0.0.0",
@@ -26753,6 +26756,7 @@
"code-fns": "^0.8.2",
"jsdom": "^21.1.0",
"mathjax-full": "^3.2.2",
+ "parse-svg-path": "^0.1.2",
"vitest": "^0.29.2"
},
"dependencies": {
@@ -35024,6 +35028,11 @@
"protocols": "^2.0.0"
}
},
+ "parse-svg-path": {
+ "version": "0.1.2",
+ "resolved": "https://registry.npmjs.org/parse-svg-path/-/parse-svg-path-0.1.2.tgz",
+ "integrity": "sha512-JyPSBnkTJ0AI8GGJLfMXvKq42cj5c006fnLz6fXy6zfoVjJizi8BNTpu8on8ziI1cKy9d9DGNuY17Ce7wuejpQ=="
+ },
"parse-url": {
"version": "8.1.0",
"resolved": "https://registry.npmjs.org/parse-url/-/parse-url-8.1.0.tgz",
diff --git a/packages/2d/package.json b/packages/2d/package.json
index 8ccbe597..a27a93ce 100644
--- a/packages/2d/package.json
+++ b/packages/2d/package.json
@@ -32,6 +32,7 @@
"dependencies": {
"@motion-canvas/core": "^3.9.0",
"code-fns": "^0.8.2",
- "mathjax-full": "^3.2.2"
+ "mathjax-full": "^3.2.2",
+ "parse-svg-path": "^0.1.2"
}
}
diff --git a/packages/2d/src/components/Curve.ts b/packages/2d/src/components/Curve.ts
index c8600536..c6170c68 100644
--- a/packages/2d/src/components/Curve.ts
+++ b/packages/2d/src/components/Curve.ts
@@ -153,6 +153,8 @@ export abstract class Curve extends Shape {
@signal()
public declare readonly arrowSize: SimpleSignal<number, this>;
+ protected canHaveSubpath = false;
+
protected override desiredSize(): SerializedVector2<DesiredLength> {
return this.childrenBBox().size;
}
@@ -243,9 +245,21 @@ export abstract class Curve extends Shape {
return Math.abs(this.start() - this.end());
}
+ protected processSubpath(
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ _path: Path2D,
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ _startPoint: Vector2 | null,
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ _endPoint: Vector2 | null,
+ ) {
+ // do nothing
+ }
+
@computed()
protected curveDrawingInfo(): CurveDrawingInfo {
const path = new Path2D();
+ let subpath = new Path2D();
const profile = this.profile();
let start = this.percentageToDistance(this.start());
@@ -283,8 +297,19 @@ export abstract class Curve extends Shape {
const clampedStart = clamp(0, 1, relativeStart);
const clampedEnd = clamp(0, 1, relativeEnd);
+ if (
+ this.canHaveSubpath &&
+ endPoint &&
+ !segment.getPoint(0).position.equals(endPoint)
+ ) {
+ path.addPath(subpath);
+ this.processSubpath(subpath, startPoint, endPoint);
+ subpath = new Path2D();
+ startPoint = null;
+ }
+
const [startCurvePoint, endCurvePoint] = segment.draw(
- path,
+ subpath,
clampedStart,
clampedEnd,
startPoint === null,
@@ -303,8 +328,10 @@ export abstract class Curve extends Shape {
}
if (this.end() === 1 && this.closed()) {
- path.closePath();
+ subpath.closePath();
}
+ this.processSubpath(subpath, startPoint, endPoint);
+ path.addPath(subpath);
return {
startPoint: startPoint ?? Vector2.zero,
diff --git a/packages/2d/src/components/Path.ts b/packages/2d/src/components/Path.ts
new file mode 100644
index 00000000..3aa8cb5f
--- /dev/null
+++ b/packages/2d/src/components/Path.ts
@@ -0,0 +1,130 @@
+import {
+ createSignal,
+ isReactive,
+ SignalValue,
+ SimpleSignal,
+} from '@motion-canvas/core/lib/signals';
+import {BBox, Vector2} from '@motion-canvas/core/lib/types';
+import {CurveProfile} from '../curves';
+import {getPathProfile} from '../curves/getPathProfile';
+import {computed, signal} from '../decorators';
+import {drawLine, drawPivot} from '../utils';
+import {Curve, CurveProps} from './Curve';
+import {threadable} from '@motion-canvas/core/lib/decorators';
+import {TimingFunction, tween} from '@motion-canvas/core/lib/tweening';
+import {createCurveProfileLerp} from '../curves/createCurveProfileLerp';
+
+export interface PathProps extends CurveProps {
+ data: SignalValue<string>;
+}
+
+export class Path extends Curve {
+ private currentProfile = createSignal<CurveProfile | null>(null);
+ @signal()
+ public declare readonly data: SimpleSignal<string, this>;
+
+ public constructor(props: PathProps) {
+ super(props);
+ this.canHaveSubpath = true;
+ }
+
+ @computed()
+ public override profile(): CurveProfile {
+ return this.currentProfile() ?? getPathProfile(this.data());
+ }
+
+ protected override childrenBBox() {
+ const points = this.profile().segments.flatMap(segment => segment.points);
+ return BBox.fromPoints(...points);
+ }
+
+ protected override lineWidthCoefficient(): number {
+ const join = this.lineJoin();
+
+ let coefficient = super.lineWidthCoefficient();
+
+ if (join === 'miter') {
+ const {minSin} = this.profile();
+ if (minSin > 0) {
+ coefficient = Math.max(coefficient, 0.5 / minSin);
+ }
+ }
+
+ return coefficient;
+ }
+
+ protected override processSubpath(
+ path: Path2D,
+ startPoint: Vector2 | null,
+ endPoint: Vector2 | null,
+ ): void {
+ if (startPoint && endPoint && startPoint.equals(endPoint)) {
+ path.closePath();
+ }
+ }
+
+ @threadable()
+ protected *tweenData(
+ newPath: SignalValue<string>,
+ time: number,
+ timingFunction: TimingFunction,
+ ) {
+ const fromProfile = this.profile();
+ const toProfile = getPathProfile(isReactive(newPath) ? newPath() : newPath);
+
+ const interpolator = createCurveProfileLerp(fromProfile, toProfile);
+
+ this.currentProfile(fromProfile);
+ yield* tween(
+ time,
+ value => {
+ const progress = timingFunction(value);
+ this.currentProfile(interpolator(progress));
+ },
+ () => {
+ this.currentProfile(null);
+ this.data(newPath);
+ },
+ );
+ }
+
+ public override drawOverlay(
+ context: CanvasRenderingContext2D,
+ matrix: DOMMatrix,
+ ): void {
+ const box = this.childrenBBox().transformCorners(matrix);
+ const size = this.computedSize();
+ const offset = size.mul(this.offset()).scale(0.5).transformAsPoint(matrix);
+ const segments = this.profile().segments;
+
+ context.lineWidth = 1;
+ context.strokeStyle = 'white';
+ context.fillStyle = 'white';
+
+ context.save();
+ context.setTransform(matrix);
+ let endPoint: Vector2 | null = null;
+ let path = new Path2D();
+
+ for (const segment of segments) {
+ if (endPoint && !segment.getPoint(0).position.equals(endPoint)) {
+ context.stroke(path);
+ path = new Path2D();
+ endPoint = null;
+ }
+ const [, end] = segment.draw(path, 0, 1, endPoint == null);
+ endPoint = end.position;
+ }
+ context.stroke(path);
+ context.restore();
+
+ context.beginPath();
+ drawPivot(context, offset);
+ context.stroke();
+
+ context.beginPath();
+ drawLine(context, box);
+ context.closePath();
+ context.stroke();
+ }
+}
diff --git a/packages/2d/src/components/index.ts b/packages/2d/src/components/index.ts
index 616c486b..b60023c6 100644
--- a/packages/2d/src/components/index.ts
+++ b/packages/2d/src/components/index.ts
@@ -13,6 +13,7 @@ export * from './Node';
export * from './Ray';
export * from './Rect';
export * from './Polygon';
+export * from './Path';
export * from './QuadBezier';
export * from './Shape';
export * from './Spline';
diff --git a/packages/2d/src/curves/ArcSegment.ts b/packages/2d/src/curves/ArcSegment.ts
new file mode 100644
index 00000000..ecb727e9
--- /dev/null
+++ b/packages/2d/src/curves/ArcSegment.ts
@@ -0,0 +1,149 @@
+import {lazy} from '@motion-canvas/core/lib/decorators';
+import {BBox, Matrix2D, Vector2} from '@motion-canvas/core/lib/types';
+import {CurvePoint} from './CurvePoint';
+import {Segment} from './Segment';
+import {DEG2RAD} from '@motion-canvas/core/lib/utils';
+import {View2D} from '../components';
+
+export class ArcSegment extends Segment {
+ @lazy(() => {
+ const root = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
+ const el = document.createElementNS('http://www.w3.org/2000/svg', 'path');
+ root.appendChild(el);
+ View2D.shadowRoot.appendChild(root);
+ return el;
+ })
+ private static el: SVGPathElement;
+ public readonly center: Vector2;
+ // angle in radian
+ public readonly startAngle: number;
+ public readonly deltaAngle: number;
+ public readonly xAxisRotation: number;
+ private xAxisRotationMatrix: DOMMatrix;
+ public override readonly points: Vector2[];
+ private length: number;
+
+ public constructor(
+ public readonly startPoint: Vector2,
+ public readonly radius: Vector2,
+ public readonly xAxisRotationDegree: number,
+ public readonly largeArcFlag: number,
+ public readonly sweepFlag: number,
+ public readonly endPoint: Vector2,
+ ) {
+ super();
+
+ this.xAxisRotation = this.xAxisRotationDegree * DEG2RAD;
+ this.radius = new Vector2(Math.abs(radius.x), Math.abs(radius.y));
+
+ const pAccent = startPoint
+ .sub(endPoint)
+ .div(2)
+ .transform(Matrix2D.fromRotation(-xAxisRotationDegree).domMatrix);
+
+ const L =
+ (pAccent.x * pAccent.x) / (radius.x * radius.x) +
+ (pAccent.y * pAccent.y) / (radius.y * radius.y);
+
+ if (L > 1) {
+ const Lsqrt = Math.sqrt(L);
+ radius.x = Lsqrt * radius.x;
+ radius.y = Lsqrt * radius.y;
+ }
+
+ const cAccent = new Vector2(
+ radius.ctg * pAccent.y,
+ radius.perpendicular.ctg * pAccent.x,
+ ).scale(
+ Math.sqrt(
+ 1 /
+ ((pAccent.x * pAccent.x) / (radius.x * radius.x) +
+ (pAccent.y * pAccent.y) / (radius.y * radius.y)) -
+ 1,
+ ) * (largeArcFlag === sweepFlag ? -1 : 1),
+ );
+
+ this.xAxisRotationMatrix =
+ Matrix2D.fromRotation(xAxisRotationDegree).domMatrix;
+ this.center = cAccent
+ .transform(this.xAxisRotationMatrix)
+ .add(startPoint.add(endPoint).div(2));
+
+ const q = pAccent.sub(cAccent).div(radius);
+ const s = pAccent.scale(-1).sub(cAccent).div(radius);
+ this.startAngle = q.radians;
+ this.deltaAngle = Vector2.angleBetween(q, s) % (Math.PI * 2);
+ if (this.sweepFlag === 0 && this.deltaAngle > 0)
+ this.deltaAngle -= Math.PI * 2;
+ if (this.sweepFlag === 1 && this.deltaAngle < 0)
+ this.deltaAngle += Math.PI * 2;
+
+ ArcSegment.el.setAttribute(
+ 'd',
+ `M ${this.startPoint.x} ${this.startPoint.y} A ${this.radius.x} ${this.radius.y} ${this.xAxisRotationDegree} ${this.largeArcFlag} ${this.sweepFlag} ${this.endPoint.x} ${this.endPoint.y}`,
+ );
+ this.length = ArcSegment.el.getTotalLength();
+
+ const bbox = new BBox(ArcSegment.el.getBBox());
+ this.points = [bbox.topLeft, bbox.bottomRight];
+ }
+
+ public getAnglePosition(angle: number) {
+ return this.radius
+ .mul(Vector2.fromRadians(angle))
+ .transform(this.xAxisRotationMatrix)
+ .add(this.center);
+ }
+
+ public getAngleDerivative(angle: number) {
+ return new Vector2(
+ -this.radius.x * Math.sin(angle),
+ this.radius.y * Math.cos(angle),
+ ).transform(this.xAxisRotationMatrix);
+ }
+
+ public draw(
+ context: CanvasRenderingContext2D | Path2D,
+ start: number,
+ end: number,
+ move: boolean,
+ ): [CurvePoint, CurvePoint] {
+ const startAngle = this.startAngle + this.deltaAngle * start;
+ const endAngle = this.startAngle + this.deltaAngle * end;
+ const startPos = this.getPoint(start);
+ const endPos = this.getPoint(end);
+
+ if (move) context.moveTo(startPos.position.x, startPos.position.y);
+
+ context.ellipse(
+ this.center.x,
+ this.center.y,
+ this.radius.x,
+ this.radius.y,
+ this.xAxisRotation,
+ startAngle,
+ endAngle,
+ this.sweepFlag === 0,
+ );
+
+ return [startPos, endPos];
+ }
+
+ public getPoint(distance: number): CurvePoint {
+ const angle = this.startAngle + distance * this.deltaAngle;
+ const tangent = this.getAngleDerivative(angle).normalized;
+ return {
+ position:
+ distance == 0
+ ? this.startPoint
+ : distance == 1
+ ? this.endPoint
+ : this.getAnglePosition(angle),
+ tangent,
+ normal: tangent.perpendicular,
+ };
+ }
+ public get arcLength(): number {
+ return this.length;
+ }
+}
diff --git a/packages/2d/src/curves/CircleSegment.ts b/packages/2d/src/curves/CircleSegment.ts
index e97164d7..be25c29b 100644
--- a/packages/2d/src/curves/CircleSegment.ts
+++ b/packages/2d/src/curves/CircleSegment.ts
@@ -6,6 +6,7 @@ import {CurvePoint} from './CurvePoint';
export class CircleSegment extends Segment {
private readonly length: number;
private readonly angle: number;
+ public override readonly points: Vector2[];
public constructor(
private center: Vector2,
@@ -17,6 +18,8 @@ export class CircleSegment extends Segment {
super();
this.angle = Math.acos(clamp(-1, 1, from.dot(to)));
this.length = Math.abs(this.angle * radius);
+ const edgeVector = new Vector2(1, 1).scale(radius);
+ this.points = [center.sub(edgeVector), center.add(edgeVector)];
}
public get arcLength(): number {
diff --git a/packages/2d/src/curves/LineSegment.ts b/packages/2d/src/curves/LineSegment.ts
index 02b03b82..e702249b 100644
--- a/packages/2d/src/curves/LineSegment.ts
+++ b/packages/2d/src/curves/LineSegment.ts
@@ -7,12 +7,17 @@ export class LineSegment extends Segment {
private readonly length: number;
private readonly vector: Vector2;
private readonly normal: Vector2;
+ public override readonly points: Vector2[];
- public constructor(private from: Vector2, private to: Vector2) {
+ public constructor(
+ public readonly from: Vector2,
+ public readonly to: Vector2,
+ ) {
super();
this.vector = to.sub(from);
this.length = this.vector.magnitude;
this.normal = this.vector.perpendicular.normalized.safe;
+ this.points = [from, to];
}
public get arcLength(): number {
diff --git a/packages/2d/src/curves/PolynomialSegment.ts b/packages/2d/src/curves/PolynomialSegment.ts
index 2ae25dbd..2955ae68 100644
--- a/packages/2d/src/curves/PolynomialSegment.ts
+++ b/packages/2d/src/curves/PolynomialSegment.ts
@@ -12,7 +12,7 @@ export abstract class PolynomialSegment extends Segment {
return this.length;
}
- public abstract get points(): Vector2[];
+ public abstract override get points(): Vector2[];
protected constructor(
protected readonly curve: Polynomial2D,
diff --git a/packages/2d/src/curves/Segment.ts b/packages/2d/src/curves/Segment.ts
index 41f103a5..ce7d321c 100644
--- a/packages/2d/src/curves/Segment.ts
+++ b/packages/2d/src/curves/Segment.ts
@@ -1,6 +1,9 @@
+import {Vector2} from '@motion-canvas/core/lib/types';
import {CurvePoint} from './CurvePoint';
export abstract class Segment {
+ public abstract readonly points: Vector2[];
+
public abstract draw(
context: CanvasRenderingContext2D | Path2D,
start: number,
diff --git a/packages/2d/src/curves/createCurveProfileLerp.ts b/packages/2d/src/curves/createCurveProfileLerp.ts
new file mode 100644
index 00000000..8e1c75fb
--- /dev/null
+++ b/packages/2d/src/curves/createCurveProfileLerp.ts
@@ -0,0 +1,471 @@
+import {Vector2} from '@motion-canvas/core/lib/types';
+import {CurveProfile} from './CurveProfile';
+import {LineSegment} from './LineSegment';
+import {getPointAtDistance} from './getPointAtDistance';
+import {getPolylineProfile} from './getPolylineProfile';
+
+// Based on kute.js svgMorph plugin
+
+interface SubcurveProfile extends CurveProfile {
+ closed: boolean;
+}
+
+interface PolygonProfile {
+ /**
+ * If path closed, first point and last point must be equal
+ */
+ points: Vector2[];
+ closed: boolean;
+}
+
+/**
+ * Split segments of polygon until distance between adjacent point is less than or equal maxLength. This function mutate original points.
+ * @param points - Polygon points
+ * @param maxLength - max distance between two point
+ */
+
+function bisect(points: Vector2[], maxLength: number) {
+ for (let i = 0; i < points.length - 1; i++) {
+ const a = points[i];
+ let b = points[i + 1];
+ while (a.sub(b).magnitude > maxLength) {
+ b = Vector2.lerp(a, b, 0.5);
+ points.splice(i + 1, 0, b);
+ }
+ }
+}
+
+/**
+ * Convert curve which only contain LineSegment into polygon.
+ * @param curve - curve to convert. curve must contain 1 subpath
+ * @param maxLength - max distance between two point
+ * @returns - null if curve contain segment other than LineSegment
+ */
+
+function exactPolygonPoints(
+ curve: SubcurveProfile,
+ maxLength: number,
+): Vector2[] | null {
+ const points: Vector2[] = [];
+
+ let endPoint: Vector2 | null = null;
+ for (const segment of curve.segments) {
+ if (!(segment instanceof LineSegment)) return null;
+
+ points.push(segment.from);
+
+ endPoint = segment.to;
+ }
+
+ if (endPoint) points.push(endPoint);
+
+ if (!Number.isNaN(maxLength) && maxLength > 0) {
+ bisect(points, maxLength);
+ }
+
+ return points;
+}
+
+/**
+ * Calculate area of polygon
+ * @param points - polygon points
+ * @returns - area of polygon
+ */
+
+function polygonArea(points: Vector2[]) {
+ return (
+ points.reduce((area, a, i) => {
+ const b = points[(i + 1) % points.length];
+ return area + (a.y * b.x - a.x * b.y);
+ }, 0) / 2
+ );
+}
+
+/**
+ * Convert curve into polygon by sampling curve profile
+ * @param curve - curve to convert. curve must contain only 1 subpath
+ * @param maxLength - max distance between point
+ * @returns - always return polygon points
+ */
+
+function approximatePolygonPoints(
+ curve: SubcurveProfile,
+ maxLength: number,
+): Vector2[] {
+ const points: Vector2[] = [];
+
+ let numPoints = 3;
+ if (!Number.isNaN(maxLength) && maxLength > 0) {
+ numPoints = Math.max(numPoints, Math.ceil(curve.arcLength / maxLength));
+ }
+
+ for (let i = 0; i < numPoints; i += 1) {
+ const point = getPointAtDistance(
+ curve,
+ curve.arcLength * (i / (numPoints - 1)),
+ );
+ points.push(point.position);
+ }
+
+ if (polygonArea(points) > 0) points.reverse();
+
+ return points;
+}
+
+/**
+ * Split curve into subpaths
+ * @param curve - curve to split
+ * @returns - subpaths of curve
+ */
+
+function splitCurve(curve: CurveProfile) {
+ if (curve.segments.length == 0) return [];
+
+ let current: SubcurveProfile = {
+ arcLength: 0,
+ minSin: 0,
+ segments: [],
+ closed: false,
+ };
+
+ let endPoint: Vector2 | null = null;
+
+ const composite: SubcurveProfile[] = [current];
+
+ for (const segment of curve.segments) {
+ const start = segment.getPoint(0).position;
+
+ if (endPoint && !start.equals(endPoint)) {
+ current = {
+ arcLength: 0,
+ minSin: 0,
+ segments: [],
+ closed: false,
+ };
+ composite.push(current);
+ }
+
+ current.segments.push(segment);
+ current.arcLength += segment.arcLength;
+ endPoint = segment.getPoint(1).position;
+ }
+
+ for (const sub of composite) {
+ sub.closed = sub.segments[0]
+ .getPoint(0)
+ .position.equals(
+ sub.segments[sub.segments.length - 1].getPoint(1).position,
+ );
+ }
+
+ return composite;
+}
+
+/**
+ * Convert curve into polygon use best possible method
+ * @param curve - curve to convert
+ * @param maxLength - max distance between two point
+ * @returns - polgon points
+ */
+
+function subcurveToPolygon(
+ curve: SubcurveProfile,
+ maxLength: number,
+): PolygonProfile {
+ const points =
+ exactPolygonPoints(curve, maxLength) ||
+ approximatePolygonPoints(curve, maxLength);
+ return {
+ points: [...points],
+ closed: curve.closed,
+ };
+}
+
+/**
+ * Calculate polygon perimeter
+ * @param points - polygon points
+ * @returns - perimeter of polygon
+ */
+
+function polygonLength(points: Vector2[]) {
+ return points.reduce((length, point, i) => {
+ if (i) return length + points[i - 1].sub(point).magnitude;
+ return 0;
+ }, 0);
+}
+
+/**s
+ * Sample additional points for polygon to better match its pair. This will mutate original points.
+ * @param points - polygon points
+ * @param numPoints - number of points to be added
+ */
+
+function addPoints(points: Vector2[], numPoints: number) {
+ const desiredLength = points.length + numPoints;
+ const step = polygonLength(points) / numPoints;
+
+ let i = 0;
+ let cursor = 0;
+ let insertAt = step / 2;
+
+ while (points.length < desiredLength) {
+ const a = points[i];
+ const b = points[(i + 1) % points.length];
+ const length = a.sub(b).magnitude;
+
+ if (insertAt <= cursor + length) {
+ points.splice(
+ i + 1,
+ 0,
+ length
+ ? Vector2.lerp(a, b, (insertAt - cursor) / length)
+ : new Vector2(a),
+ );
+ insertAt += step;
+ } else {
+ cursor += length;
+ i += 1;
+ }
+ }
+}
+
+/**
+ * Calculate total moving point distance when morphing between polygon points
+ * @param points - first polygon points
+ * @param reference - second polygon points
+ * @param offset - offset for first polygon points
+ * @returns
+ */
+
+function calculateLerpDistance(
+ points: Vector2[],
+ reference: Vector2[],
+ offset: number,
+) {
+ const len = points.length;
+ let sumOfSquares = 0;
+
+ for (let i = 0; i < reference.length; i += 1) {
+ const a = points[(offset + i) % len];
+ const b = reference[i];
+ sumOfSquares += a.sub(b).squaredMagnitude;
+ }
+
+ return sumOfSquares;
+}
+
+/**
+ * Rotate polygon in order to minimize moving points.
+ * @param polygon - polygon to be rotated
+ * @param reference - polygon to be reference
+ */
+
+function rotatePolygon(polygon: PolygonProfile, reference: PolygonProfile) {
+ const {points, closed} = polygon;
+ const len = points.length;
+
+ if (!closed) {
+ const originalDistance = calculateLerpDistance(points, reference.points, 0);
+ const reversedPoints = [...points].reverse();
+ const reversedDistance = calculateLerpDistance(
+ reversedPoints,
+ reference.points,
+ 0,
+ );
+ if (reversedDistance < originalDistance) polygon.points = reversedPoints;
+ } else {
+ let minDistance = Infinity;
+ let bestOffset = 0;
+ const last = points.pop();
+
+ // Closed polygon first point must equal last point
+ // When we rotate polygon, first point is changed which mean last point also must changed
+ // When we remove last point, calculateLerpDistance will assume last point is equal first point
+ // Proof:
+ // len = points.length = reference.length - 1
+ // When i = 0:
+ // (offset + i) % len = offset % len
+ // When i = reference.length - 1 or i = len
+ // (offset + i) % len = (offset + len) % len = offset % len
+
+ for (let offset = 0; offset < len; offset += 1) {
+ const distance = calculateLerpDistance(points, reference.points, offset);
+ if (distance < minDistance) {
+ minDistance = distance;
+ bestOffset = offset;
+ }
+ }
+
+ if (last) points.push(last);
+
+ if (bestOffset) {
+ points.pop();
+ const spliced = points.splice(0, bestOffset);
+ points.splice(points.length, 0, ...spliced);
+ points.push(points[0]);
+ }
+ }
+}
+
+/**
+ * Round polygon's points coordinate to a specified amount of decimal
+ * @param points - polygon point to be rounded
+ * @param round - amount of decimal
+ * @returns - new polygon point
+ */
+
+function roundPolygon(
+ {points, ...rest}: PolygonProfile,
+ round: number,
+): PolygonProfile {
+ const pow = round >= 1 ? 10 ** round : 1;
+ return {
+ points: points.map(point => {
+ const [x, y] = [point.x, point.y].map(n => Math.round(n * pow) / pow);
+ return new Vector2(x, y);
+ }),
+ ...rest,
+ };
+}
+
+/**
+ * Create two polygon to tween between sub curve/path
+ * @param from - source curve
+ * @param to - targe curve
+ * @param precision - desired distance between two point
+ * @param round - amount of decimal when rounding
+ * @returns two polygon ready to tween
+ */
+
+function getSubcurveInterpolationPolygon(
+ from: SubcurveProfile,
+ to: SubcurveProfile,
+ precision: number,
+ round: number,
+) {
+ const morphPrecision = precision;
+ const fromRing = subcurveToPolygon(from, morphPrecision);
+ const toRing = subcurveToPolygon(to, morphPrecision);
+
+ const diff = fromRing.points.length - toRing.points.length;
+
+ addPoints(fromRing.points, diff < 0 ? diff * -1 : 0);
+ addPoints(toRing.points, diff > 0 ? diff : 0);
+
+ if (!from.closed && to.closed) rotatePolygon(toRing, fromRing);
+ else rotatePolygon(fromRing, toRing);
+
+ return {
+ from: roundPolygon(fromRing, round),
+ to: roundPolygon(toRing, round),
+ };
+}
+
+/**
+ * Make two sub curve list have equal length
+ * @param subcurves - List to add
+ * @param reference - Reference list
+ */
+
+function balanceSubcurves(
+ subcurves: SubcurveProfile[],
+ reference: SubcurveProfile[],
+) {
+ for (let i = subcurves.length; i < reference.length; i++) {
+ const point = reference[i].segments[0].getPoint(0).position;
+ subcurves.push({
+ arcLength: 0,
+ closed: false,
+ minSin: 0,
+ segments: [new LineSegment(point, point)],
+ });
+ }
+}
+
+/**
+ * Create two polygon to tween between curve
+ * @param from - source curve
+ * @param to - targe curve
+ * @param precision - desired distance between two point
+ * @param round - amount of decimal when rounding
+ * @returns list that contain list of polygon before and after tween
+ */
+
+function getInterpolationPolygon(
+ from: CurveProfile,
+ to: CurveProfile,
+ precision: number,
+ round: number,
+) {
+ const fromSub = splitCurve(from);
+ const toSub = splitCurve(to);
+
+ if (fromSub.length < toSub.length) balanceSubcurves(fromSub, toSub);
+ else balanceSubcurves(toSub, fromSub);
+
+ return fromSub.map((sub, i) =>
+ getSubcurveInterpolationPolygon(sub, toSub[i], precision, round),
+ );
+}
+
+/**
+ * Add curve into another curve
+ * @param target - target curve
+ * @param source - curve to add
+ */
+
+function addCurveToCurve(target: CurveProfile, source: CurveProfile) {
+ const {segments, arcLength, minSin} = source;
+ target.segments.push(...segments);
+ target.arcLength += arcLength;
+ target.minSin = Math.min(target.minSin, minSin);
+}
+
+/**
+ * Interpolate between two polygon points.
+ * @param from - source polygon points
+ * @param to - target polygon points
+ * @param value - interpolation progress
+ * @returns - new polygon points
+ */
+
+function polygonPointsLerp(
+ from: Vector2[],
+ to: Vector2[],
+ value: number,
+): Vector2[] {
+ const points: Vector2[] = [];
+ if (value === 0) return [...from];
+ if (value === 1) return [...to];
+
+ for (let i = 0; i < from.length; i++) {
+ const a = from[i];
+ const b = to[i];
+ points.push(Vector2.lerp(a, b, value));
+ }
+ return points;
+}
+
+/**
+ * Create interpolator to tween between two curve
+ * @param a - source curve
+ * @param b - target curve
+ * @returns - curve interpolator
+ */
+
+export function createCurveProfileLerp(a: CurveProfile, b: CurveProfile) {
+ const interpolations = getInterpolationPolygon(a, b, 5, 4);
+
+ return (progress: number) => {
+ const curve: CurveProfile = {
+ segments: [],
+ arcLength: 0,
+ minSin: 1,
+ };
+ for (const {from, to} of interpolations) {
+ const points = polygonPointsLerp(from.points, to.points, progress);
+ addCurveToCurve(curve, getPolylineProfile(points, 0, false));
+ }
+ return curve;
+ };
+}
diff --git a/packages/2d/src/curves/getPathProfile.ts b/packages/2d/src/curves/getPathProfile.ts
new file mode 100644
index 00000000..1c796e2f
--- /dev/null
+++ b/packages/2d/src/curves/getPathProfile.ts
@@ -0,0 +1,178 @@
+import {clamp} from '@motion-canvas/core/lib/tweening';
+import {Vector2} from '@motion-canvas/core/lib/types';
+import {ArcSegment} from './ArcSegment';
+import {CubicBezierSegment} from './CubicBezierSegment';
+import {CurveProfile} from './CurveProfile';
+import {LineSegment} from './LineSegment';
+import {QuadBezierSegment} from './QuadBezierSegment';
+import {Segment} from './Segment';
+import parse, {PathCommand} from 'parse-svg-path';
+
+function addSegmentToProfile(profile: CurveProfile, segment: Segment) {
+ profile.segments.push(segment);
+ profile.arcLength += segment.arcLength;
+}
+
+function getArg(command: PathCommand, argumentIndex: number) {
+ return command[argumentIndex + 1] as number;
+}
+
+function getVector2(command: PathCommand, argumentIndex: number) {
+ return new Vector2(
+ command[argumentIndex + 1] as number,
+ command[argumentIndex + 2] as number,
+ );
+}
+
+function getPoint(
+ command: PathCommand,
+ argumentIndex: number,
+ isRelative: boolean,
+ currentPoint: Vector2,
+) {
+ const point = getVector2(command, argumentIndex);
+ return isRelative ? currentPoint.add(point) : point;
+}
+
+function reflectControlPoint(control: Vector2, currentPoint: Vector2) {
+ return currentPoint.add(currentPoint.sub(control));
+}
+
+function updateMinSin(profile: CurveProfile) {
+ for (let i = 0; i < profile.segments.length; i++) {
+ const segmentA = profile.segments[i];
+ const segmentB = profile.segments[(i + 1) % profile.segments.length];
+
+ // In cubic bezier this equal p2.sub(p3)
+ const startVector = segmentA.getPoint(1).tangent.scale(-1);
+ // In cubic bezier this equal p1.sub(p0)
+ const endVector = segmentB.getPoint(0).tangent;
+ const dot = startVector.dot(endVector);
+
+ const angleBetween = Math.acos(clamp(-1, 1, dot));
+ const angleSin = Math.sin(angleBetween / 2);
+
+ profile.minSin = Math.min(profile.minSin, Math.abs(angleSin));
+ }
+}
+
+export function getPathProfile(data: string): CurveProfile {
+ const profile: CurveProfile = {
+ segments: [],
+ arcLength: 0,
+ minSin: 1,
+ };
+
+ const segments = parse(data);
+ let currentPoint = new Vector2(0, 0);
+ let firstPoint: Vector2 | null = null;
+
+ for (const segment of segments) {
+ const command = segment[0].toLowerCase();
+ const isRelative = segment[0] === command;
+
+ if (command === 'm') {
+ currentPoint = getPoint(segment, 0, isRelative, currentPoint);
+ firstPoint = currentPoint;
+ } else if (command === 'l') {
+ const nextPoint = getPoint(segment, 0, isRelative, currentPoint);
+ addSegmentToProfile(profile, new LineSegment(currentPoint, nextPoint));
+ currentPoint = nextPoint;
+ } else if (command === 'h') {
+ const x = getArg(segment, 0);
+ const nextPoint = isRelative
+ ? currentPoint.addX(x)
+ : new Vector2(x, currentPoint.y);
+ addSegmentToProfile(profile, new LineSegment(currentPoint, nextPoint));
+ currentPoint = nextPoint;
+ } else if (command === 'v') {
+ const y = getArg(segment, 0);
+ const nextPoint = isRelative
+ ? currentPoint.addY(y)
+ : new Vector2(currentPoint.x, y);
+ addSegmentToProfile(profile, new LineSegment(currentPoint, nextPoint));
+ currentPoint = nextPoint;
+ } else if (command === 'q') {
+ const controlPoint = getPoint(segment, 0, isRelative, currentPoint);
+ const nextPoint = getPoint(segment, 2, isRelative, currentPoint);
+ addSegmentToProfile(
+ profile,
+ new QuadBezierSegment(currentPoint, controlPoint, nextPoint),
+ );
+ currentPoint = nextPoint;
+ } else if (command === 't') {
+ const lastSegment = profile.segments.at(-1);
+ const controlPoint =
+ lastSegment instanceof QuadBezierSegment
+ ? reflectControlPoint(lastSegment.p1, currentPoint)
+ : currentPoint;
+
+ const nextPoint = getPoint(segment, 0, isRelative, currentPoint);
+ addSegmentToProfile(
+ profile,
+ new QuadBezierSegment(currentPoint, controlPoint, nextPoint),
+ );
+ currentPoint = nextPoint;
+ } else if (command === 'c') {
+ const startControlPoint = getPoint(segment, 0, isRelative, currentPoint);
+ const endControlPoint = getPoint(segment, 2, isRelative, currentPoint);
+ const nextPoint = getPoint(segment, 4, isRelative, currentPoint);
+ addSegmentToProfile(
+ profile,
+ new CubicBezierSegment(
+ currentPoint,
+ startControlPoint,
+ endControlPoint,
+ nextPoint,
+ ),
+ );
+ currentPoint = nextPoint;
+ } else if (command === 's') {
+ const lastSegment = profile.segments.at(-1);
+ const startControlPoint =
+ lastSegment instanceof CubicBezierSegment
+ ? reflectControlPoint(lastSegment.p2, currentPoint)
+ : currentPoint;
+
+ const endControlPoint = getPoint(segment, 0, isRelative, currentPoint);
+ const nextPoint = getPoint(segment, 2, isRelative, currentPoint);
+ addSegmentToProfile(
+ profile,
+ new CubicBezierSegment(
+ currentPoint,
+ startControlPoint,
+ endControlPoint,
+ nextPoint,
+ ),
+ );
+ currentPoint = nextPoint;
+ } else if (command === 'a') {
+ const radius = getVector2(segment, 0);
+ const angle = getArg(segment, 2);
+ const largeArcFlag = getArg(segment, 3);
+ const sweepFlag = getArg(segment, 4);
+ const nextPoint = getPoint(segment, 5, isRelative, currentPoint);
+ addSegmentToProfile(
+ profile,
+ new ArcSegment(
+ currentPoint,
+ radius,
+ angle,
+ largeArcFlag,
+ sweepFlag,
+ nextPoint,
+ ),
+ );
+ currentPoint = nextPoint;
+ } else if (command === 'z') {
+ if (!firstPoint) continue;
+ if (currentPoint.equals(firstPoint)) continue;
+
+ addSegmentToProfile(profile, new LineSegment(currentPoint, firstPoint));
+ currentPoint = firstPoint;
+ }
+ }
+ updateMinSin(profile);
+
+ return profile;
+}
diff --git a/packages/2d/src/parse-svg-path.d.ts b/packages/2d/src/parse-svg-path.d.ts
new file mode 100644
index 00000000..d94813e7
--- /dev/null
+++ b/packages/2d/src/parse-svg-path.d.ts
@@ -0,0 +1,15 @@
+declare module 'parse-svg-path' {
+ import * as something from 'parse-svg-path';
+ export type PathCommand = [
+ string,
+ number,
+ number,
+ number,
+ number,
+ number,
+ number,
+ number,
+ ];
+ function parse(path: string): PathCommand[];
+ export default parse;
+}
diff --git a/packages/core/src/types/Vector.ts b/packages/core/src/types/Vector.ts
index dff2d22c..c33528b6 100644
--- a/packages/core/src/types/Vector.ts
+++ b/packages/core/src/types/Vector.ts
@@ -1,5 +1,5 @@
import {arcLerp, InterpolationFunction} from '../tweening';
-import {map} from '../tweening/interpolationFunctions';
+import {clamp, map} from '../tweening/interpolationFunctions';
import {Direction, Origin} from './Origin';
import {EPSILON, Type} from './Type';
import {
@@ -160,6 +160,13 @@ export class Vector2 implements Type {
return x * x + y * y;
}
+ public static angleBetween(u: Vector2, v: Vector2) {
+ return (
+ Math.acos(clamp(-1, 1, u.dot(v) / (u.magnitude * v.magnitude))) *
+ (u.cross(v) >= 0 ? 1 : -1)
+ );
+ }
+
public get width(): number {
return this.x;
}
@@ -310,6 +317,11 @@ export class Vector2 implements Type {
return this.x * vector.x + this.y * vector.y;
}
+ public cross(possibleVector: PossibleVector2): number {
+ const vector = new Vector2(possibleVector);
+ return this.x * vector.y - this.y * vector.x;
+ }
+
public mod(possibleVector: PossibleVector2): Vector2 {
const vector = new Vector2(possibleVector);
return new Vector2(this.x % vector.x, this.y % vector.y);
diff --git a/packages/docs/docs/components/custom-components.mdx b/packages/docs/docs/components/custom-components.mdx
index 987874ca..95a49266 100644
--- a/packages/docs/docs/components/custom-components.mdx
+++ b/packages/docs/docs/components/custom-components.mdx
@@ -1,5 +1,5 @@
---
-sidebar_position: 5
+sidebar_position: 6
slug: /custom-components
---
diff --git a/packages/docs/docs/components/path.mdx b/packages/docs/docs/components/path.mdx
new file mode 100644
index 00000000..c4fafec0
--- /dev/null
+++ b/packages/docs/docs/components/path.mdx
@@ -0,0 +1,104 @@
+---
+sidebar_position: 5
+slug: /path
+---
+
+# Path
+
+```tsx editor
+import {makeScene2D, Path} from '@motion-canvas/2d';
+import {createRef} from '@motion-canvas/core';
+
+export default makeScene2D(function* (view) {
+ const path = createRef<Path>();
+
+ view.add(
+ <Path
+ ref={path}
+ lineWidth={4}
+ stroke={'#e13238'}
+ data="M 151.34904,307.20455 L 264.34904,307.20455 C 264.34904,291.14096 263.2021,287.95455 236.59904,287.95455 C 240.84904,275.20455 258.12424,244.35808 267.72404,244.35808 C 276.21707,244.35808 286.34904,244.82592 286.34904,264.20455 C 286.34904,286.20455 323.37171,321.67547 332.34904,307.20455 C 345.72769,285.63897 309.34904,292.21514 309.34904,240.20455 C 309.34904,169.05135 350.87417,179.18071 350.87417,139.20455 C 350.87417,119.20455 345.34904,116.50374 345.34904,102.20455 C 345.34904,83.30695 361.99717,84.403577 358.75805,68.734879 C 356.52061,57.911656 354.76962,49.23199 353.46516,36.143889 C 352.53959,26.857305 352.24452,16.959398 342.59855,17.357382 C 331.26505,17.824992 326.96549,37.77419 309.34904,39.204549 C 291.76851,40.631991 276.77834,24.238028 269.97404,26.579549 C 263.22709,28.901334 265.34904,47.204549 269.34904,60.204549 C 275.63588,80.636771 289.34904,107.20455 264.34904,111.20455 C 239.34904,115.20455 196.34904,119.20455 165.34904,160.20455 C 134.34904,201.20455 135.49342,249.3212 123.34904,264.20455 C 82.590696,314.15529 40.823919,293.64625 40.823919,335.20455 C 40.823919,353.81019 72.349045,367.20455 77.349045,361.20455 C 82.349045,355.20455 34.863764,337.32587 87.995492,316.20455 C 133.38711,298.16014 137.43914,294.47663 151.34904,307.20455 z"
+ position={[-100, -100]}
+ scale={0.5}
+ start={0}
+ end={0}
+ ></Path>,
+ );
+
+ yield* path().end(1, 1);
+ yield* path().fill('#e13238', 1);
+});
+```
+
+This component allows us to draw and animate SVG path.
+
+## Defining Path
+
+You can define path to display by setting `data` property of Path component.
+
+## Animating Path
+
+### Morphing Between Two Path
+
+To morph between two path you can tween `data` property.
+
+```tsx editor
+import {makeScene2D, Path} from '@motion-canvas/2d';
+import {createRef} from '@motion-canvas/core';
+
+export default makeScene2D(function* (view) {
+ const path = createRef<Path>();
+
+ view.add(
+ <Path
+ ref={path}
+ lineWidth={4}
+ stroke={'#e13238'}
+ data="M301.113,12.011L576.715,584.766L25.508,584.766L301.113,12.011z"
+ position={[-100, -100]}
+ scale={0.25}
+ ></Path>,
+ );
+
+ yield* path().data(
+ 'M25.508,12.011 L576.715,12.011 L576.715,584.766 L25.508,584.766 L25.508,12.011 z',
+ 1,
+ );
+});
+```
+
+### Animating objects along a spline
+
+Like Spline and Bezier, you can also make other components follow this component
+path. You can use the `getPointAtPercentage` to get point along this path.
+
+```tsx editor
+import {makeScene2D, Path, Rect} from '@motion-canvas/2d';
+import {createRef, createSignal} from '@motion-canvas/core';
+
+export default makeScene2D(function* (view) {
+ const path = createRef<Path>();
+ const progress = createSignal(0);
+
+ view.add(
+ <>
+ <Path
+ ref={path}
+ lineWidth={6}
+ stroke={'lightgray'}
+ data={
+ 'M -180 -21 C -180 -54.1371 -153.1371 -81 -120 -81 C -86.8629 -81 -60 -54.1371 -60 -21 C -60 12.1371 -33.1371 33 0 33 C 33.1371 33 48 3 48 -21 C 48 -45 30 -69 0 -69 C -30 -69 -48 -45 -48 -21 C -48 3 -33.1371 33 0 33 C 39 34.5 60 12 60 -21 C 60 -54.1371 86.8629 -81 120 -81 C 153.1371 -81 180 -54.1371 180 -21 C 180 12.1371 153.1371 39 120 39 L -120 39 C -153.1371 39 -180 12.1371 -180 -21 Z'
+ }
+ />
+ <Rect
+ size={26}
+ fill={'lightseagreen'}
+ position={() => path().getPointAtPercentage(progress()).position}
+ rotation={() => path().getPointAtPercentage(progress()).tangent.degrees}
+ />,
+ </>,
+ );
+
+ yield* progress(1, 2).to(0, 2);
+});
+```