Skip to content

🎥 Make videos programmatically with React

implement get bounding box

Jonny Burgerfea3b16f0d49
diff --git a/packages/paths/src/get-bounding-box.ts b/packages/paths/src/get-bounding-box.ts
new file mode 100644
index 0000000000..97ee758fef
--- /dev/null
+++ b/packages/paths/src/get-bounding-box.ts
@@ -0,0 +1,214 @@
+'use strict';
+
+import {normalizePath} from './normalize-path';
+import {unarc} from './unarc';
+import {unshort} from './unshort';
+
+type minMax = [min: number, max: number];
+export type BBox = [minX: number, minY: number, maxX: number, maxY: number];
+
+// Precision for consider cubic polynom as quadratic one
+const CBEZIER_MINMAX_EPSILON = 0.00000001;
+
+// https://github.com/kpym/SVGPathy/blob/acd1a50c626b36d81969f6e98e8602e128ba4302/lib/box.js#L89
+function minmaxQ(A: [number, number, number]): minMax {
+ const min = Math.min(A[0], A[2]);
+ const max = Math.max(A[0], A[2]);
+
+ if (A[1] > A[0] ? A[2] >= A[1] : A[2] <= A[1]) {
+ // if no extremum in ]0,1[
+ return [min, max];
+ }
+
+ // check if the extremum E is min or max
+ const E = (A[0] * A[2] - A[1] * A[1]) / (A[0] - 2 * A[1] + A[2]);
+ return E < min ? [E, max] : [min, E];
+}
+
+// https://github.com/kpym/SVGPathy/blob/acd1a50c626b36d81969f6e98e8602e128ba4302/lib/box.js#L127
+function minmaxC(A: [number, number, number, number]): minMax {
+ const K = A[0] - 3 * A[1] + 3 * A[2] - A[3];
+
+ // if the polynomial is (almost) quadratic and not cubic
+ if (Math.abs(K) < CBEZIER_MINMAX_EPSILON) {
+ if (A[0] === A[3] && A[0] === A[1]) {
+ // no curve, point targeting same location
+ return [A[0], A[3]];
+ }
+
+ return minmaxQ([
+ A[0],
+ -0.5 * A[0] + 1.5 * A[1],
+ A[0] - 3 * A[1] + 3 * A[2],
+ ]);
+ }
+
+ // the reduced discriminant of the derivative
+ const T =
+ -A[0] * A[2] +
+ A[0] * A[3] -
+ A[1] * A[2] -
+ A[1] * A[3] +
+ A[1] * A[1] +
+ A[2] * A[2];
+
+ // if the polynomial is monotone in [0,1]
+ if (T <= 0) {
+ return [Math.min(A[0], A[3]), Math.max(A[0], A[3])];
+ }
+
+ const S = Math.sqrt(T);
+
+ // potential extrema
+ let min = Math.min(A[0], A[3]);
+ let max = Math.max(A[0], A[3]);
+
+ const L = A[0] - 2 * A[1] + A[2];
+ // check local extrema
+ for (let R = (L + S) / K, i = 1; i <= 2; R = (L - S) / K, i++) {
+ if (R > 0 && R < 1) {
+ // if the extrema is for R in [0,1]
+ const Q =
+ A[0] * (1 - R) * (1 - R) * (1 - R) +
+ A[1] * 3 * (1 - R) * (1 - R) * R +
+ A[2] * 3 * (1 - R) * R * R +
+ A[3] * R * R * R;
+ if (Q < min) {
+ min = Q;
+ }
+
+ if (Q > max) {
+ max = Q;
+ }
+ }
+ }
+
+ return [min, max];
+}
+
+/**
+ * Compute bounding boxes of SVG paths.
+ * @param {String} d SVG path for which their bounding box will be computed.
+ * @returns {BBox}
+ */
+export default function svgPathBbox(d: string): BBox {
+ const min = [Infinity, Infinity];
+ const max = [-Infinity, -Infinity];
+ const abs = normalizePath(d);
+ const unarced = unarc(abs);
+ const unshortened = unshort(unarced);
+
+ let x = 0;
+ let y = 0;
+
+ for (const seg of unshortened) {
+ switch (seg[0]) {
+ case 'M':
+ case 'L': {
+ if (min[0] > seg[1]) {
+ min[0] = seg[1];
+ }
+
+ if (min[1] > seg[2]) {
+ min[1] = seg[2];
+ }
+
+ if (max[0] < seg[1]) {
+ max[0] = seg[1];
+ }
+
+ if (max[1] < seg[2]) {
+ max[1] = seg[2];
+ }
+
+ x = seg[1];
+ y = seg[2];
+
+ break;
+ }
+
+ case 'V': {
+ if (min[1] > seg[1]) {
+ min[1] = seg[1];
+ }
+
+ if (max[1] < seg[1]) {
+ max[1] = seg[1];
+ }
+
+ y = seg[1];
+
+ break;
+ }
+
+ case 'H': {
+ if (min[0] > seg[1]) {
+ min[0] = seg[1];
+ }
+
+ if (max[0] < seg[1]) {
+ max[0] = seg[1];
+ }
+
+ x = seg[1];
+
+ break;
+ }
+
+ case 'C': {
+ const cxMinMax = minmaxC([x, seg[1], seg[3], seg[5]]);
+ if (min[0] > cxMinMax[0]) {
+ min[0] = cxMinMax[0];
+ }
+
+ if (max[0] < cxMinMax[1]) {
+ max[0] = cxMinMax[1];
+ }
+
+ const cyMinMax = minmaxC([y, seg[2], seg[4], seg[6]]);
+ if (min[1] > cyMinMax[0]) {
+ min[1] = cyMinMax[0];
+ }
+
+ if (max[1] < cyMinMax[1]) {
+ max[1] = cyMinMax[1];
+ }
+
+ x = seg[5];
+ y = seg[6];
+
+ break;
+ }
+
+ case 'Q': {
+ const qxMinMax = minmaxQ([x, seg[1], seg[3]]);
+ if (min[0] > qxMinMax[0]) {
+ min[0] = qxMinMax[0];
+ }
+
+ if (max[0] < qxMinMax[1]) {
+ max[0] = qxMinMax[1];
+ }
+
+ const qyMinMax = minmaxQ([y, seg[2], seg[4]]);
+ if (min[1] > qyMinMax[0]) {
+ min[1] = qyMinMax[0];
+ }
+
+ if (max[1] < qyMinMax[1]) {
+ max[1] = qyMinMax[1];
+ }
+
+ x = seg[3];
+ y = seg[4];
+
+ break;
+ }
+
+ default:
+ throw new Error(`Unknown instruction ${seg[0]}`);
+ }
+ }
+
+ return [min[0], min[1], max[0], max[1]];
+}
diff --git a/packages/paths/src/unarc.ts b/packages/paths/src/unarc.ts
new file mode 100644
index 0000000000..6958972448
--- /dev/null
+++ b/packages/paths/src/unarc.ts
@@ -0,0 +1,282 @@
+import type {Instruction} from './helpers/parse';
+import {parsePath} from './helpers/parse';
+
+const TAU = Math.PI * 2;
+
+function approximate_unit_arc(theta1: number, delta_theta: number) {
+ const alpha = (4 / 3) * Math.tan(delta_theta / 4);
+
+ const x1 = Math.cos(theta1);
+ const y1 = Math.sin(theta1);
+ const x2 = Math.cos(theta1 + delta_theta);
+ const y2 = Math.sin(theta1 + delta_theta);
+
+ return [
+ x1,
+ y1,
+ x1 - y1 * alpha,
+ y1 + x1 * alpha,
+ x2 + y2 * alpha,
+ y2 - x2 * alpha,
+ x2,
+ y2,
+ ];
+}
+
+function a2c(
+ x1: number,
+ y1: number,
+ x2: number,
+ y2: number,
+ fa: number,
+ fs: number,
+ rx: number,
+ ry: number,
+ phi: number
+) {
+ const sin_phi = Math.sin((phi * TAU) / 360);
+ const cos_phi = Math.cos((phi * TAU) / 360);
+
+ // Make sure radii are valid
+ //
+ const x1p = (cos_phi * (x1 - x2)) / 2 + (sin_phi * (y1 - y2)) / 2;
+ const y1p = (-sin_phi * (x1 - x2)) / 2 + (cos_phi * (y1 - y2)) / 2;
+
+ if (x1p === 0 && y1p === 0) {
+ // we're asked to draw line to itself
+ return [];
+ }
+
+ if (rx === 0 || ry === 0) {
+ // one of the radii is zero
+ return [];
+ }
+
+ // Compensate out-of-range radii
+ //
+ rx = Math.abs(rx);
+ ry = Math.abs(ry);
+
+ const lambda = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry);
+ if (lambda > 1) {
+ rx *= Math.sqrt(lambda);
+ ry *= Math.sqrt(lambda);
+ }
+
+ // Get center parameters (cx, cy, theta1, delta_theta)
+ //
+ const cc = get_arc_center(x1, y1, x2, y2, fa, fs, rx, ry, sin_phi, cos_phi);
+
+ const result = [];
+ let theta1 = cc[2];
+ let delta_theta = cc[3];
+
+ // Split an arc to multiple segments, so each segment
+ // will be less than τ/4 (= 90°)
+ //
+ const segments = Math.max(Math.ceil(Math.abs(delta_theta) / (TAU / 4)), 1);
+ delta_theta /= segments;
+
+ for (let i = 0; i < segments; i++) {
+ result.push(approximate_unit_arc(theta1, delta_theta));
+ theta1 += delta_theta;
+ }
+
+ // We have a bezier approximation of a unit circle,
+ // now need to transform back to the original ellipse
+ //
+ return result.map((curve) => {
+ for (let i = 0; i < curve.length; i += 2) {
+ let x = curve[i + 0];
+ let y = curve[i + 1];
+
+ // scale
+ x *= rx;
+ y *= ry;
+
+ // rotate
+ const xp = cos_phi * x - sin_phi * y;
+ const yp = sin_phi * x + cos_phi * y;
+
+ // translate
+ curve[i + 0] = xp + cc[0];
+ curve[i + 1] = yp + cc[1];
+ }
+
+ return curve;
+ });
+}
+
+export const unarc = (d: string) => {
+ const segments = parsePath(d);
+ let x = 0;
+ let y = 0;
+
+ const newSegments = segments.map((s): Instruction[] => {
+ switch (s[0]) {
+ case 'M':
+ case 'L': {
+ x = s[1];
+ y = s[2];
+ return [s];
+ }
+
+ case 'A': {
+ const nextX = s[6];
+ const nextY = s[7];
+
+ const new_segments = a2c(
+ x,
+ y,
+ nextX,
+ nextY,
+ s[4],
+ s[5],
+ s[1],
+ s[2],
+ s[3]
+ );
+
+ // Degenerated arcs can be ignored by renderer, but should not be dropped
+ // to avoid collisions with `S A S` and so on. Replace with empty line.
+ if (new_segments.length === 0) {
+ return [['L', s[6], s[7]]];
+ }
+
+ const result: Instruction[] = [];
+
+ new_segments.forEach((_s) => {
+ result.push(['C', _s[2], _s[3], _s[4], _s[5], _s[6], _s[7]]);
+ });
+ return result;
+ }
+
+ case 'V': {
+ y = s[1];
+
+ return [s];
+ }
+
+ case 'H': {
+ x = s[1];
+
+ return [s];
+ }
+
+ case 'C': {
+ x = s[5];
+ y = s[6];
+
+ return [s];
+ }
+
+ case 'Q': {
+ x = s[3];
+ y = s[4];
+
+ return [s];
+ }
+
+ default:
+ throw new Error(`Unexpected instruction ${s[0]}`);
+ }
+ });
+
+ const flatted = newSegments.flat(1);
+
+ return flatted;
+};
+
+function get_arc_center(
+ x1: number,
+ y1: number,
+ x2: number,
+ y2: number,
+ fa: number,
+ fs: number,
+ rx: number,
+ ry: number,
+ sin_phi: number,
+ cos_phi: number
+) {
+ // Step 1.
+ //
+ // Moving an ellipse so origin will be the middlepoint between our two
+ // points. After that, rotate it to line up ellipse axes with coordinate
+ // axes.
+ //
+ const x1p = (cos_phi * (x1 - x2)) / 2 + (sin_phi * (y1 - y2)) / 2;
+ const y1p = (-sin_phi * (x1 - x2)) / 2 + (cos_phi * (y1 - y2)) / 2;
+
+ const rx_sq = rx * rx;
+ const ry_sq = ry * ry;
+ const x1p_sq = x1p * x1p;
+ const y1p_sq = y1p * y1p;
+
+ // Step 2.
+ //
+ // Compute coordinates of the centre of this ellipse (cx', cy')
+ // in the new coordinate system.
+ //
+ let radicant = rx_sq * ry_sq - rx_sq * y1p_sq - ry_sq * x1p_sq;
+
+ if (radicant < 0) {
+ // due to rounding errors it might be e.g. -1.3877787807814457e-17
+ radicant = 0;
+ }
+
+ radicant /= rx_sq * y1p_sq + ry_sq * x1p_sq;
+ radicant = Math.sqrt(radicant) * (fa === fs ? -1 : 1);
+
+ const cxp = ((radicant * rx) / ry) * y1p;
+ const cyp = ((radicant * -ry) / rx) * x1p;
+
+ // Step 3.
+ //
+ // Transform back to get centre coordinates (cx, cy) in the original
+ // coordinate system.
+ //
+ const cx = cos_phi * cxp - sin_phi * cyp + (x1 + x2) / 2;
+ const cy = sin_phi * cxp + cos_phi * cyp + (y1 + y2) / 2;
+
+ // Step 4.
+ //
+ // Compute angles (theta1, delta_theta).
+ //
+ const v1x = (x1p - cxp) / rx;
+ const v1y = (y1p - cyp) / ry;
+ const v2x = (-x1p - cxp) / rx;
+ const v2y = (-y1p - cyp) / ry;
+
+ const theta1 = unit_vector_angle(1, 0, v1x, v1y);
+ let delta_theta = unit_vector_angle(v1x, v1y, v2x, v2y);
+
+ if (fs === 0 && delta_theta > 0) {
+ delta_theta -= TAU;
+ }
+
+ if (fs === 1 && delta_theta < 0) {
+ delta_theta += TAU;
+ }
+
+ return [cx, cy, theta1, delta_theta];
+}
+
+function unit_vector_angle(ux: number, uy: number, vx: number, vy: number) {
+ const sign = ux * vy - uy * vx < 0 ? -1 : 1;
+ let dot = ux * vx + uy * vy;
+
+ // Add this to work with arbitrary vectors:
+ // dot /= Math.sqrt(ux * ux + uy * uy) * Math.sqrt(vx * vx + vy * vy);
+
+ // rounding errors, e.g. -1.0000000000000002 can screw up this
+ if (dot > 1.0) {
+ dot = 1.0;
+ }
+
+ if (dot < -1.0) {
+ dot = -1.0;
+ }
+
+ return sign * Math.acos(dot);
+}
diff --git a/packages/paths/src/unshort.ts b/packages/paths/src/unshort.ts
new file mode 100644
index 0000000000..87b0276c3e
--- /dev/null
+++ b/packages/paths/src/unshort.ts
@@ -0,0 +1,134 @@
+import type {Instruction} from './helpers/parse';
+
+export const unshort = function (segments: Instruction[]): Instruction[] {
+ let prevControlX = 0;
+ let prevControlY = 0;
+ let curControlX = 0;
+ let curControlY = 0;
+
+ let x = 0;
+ let y = 0;
+
+ const newSegments = segments.slice(0);
+
+ for (let i = 0; i < newSegments.length; i++) {
+ const s = newSegments[i];
+ const name = s[0];
+ switch (s[0]) {
+ case 'M':
+ case 'L': {
+ x = s[1];
+ y = s[2];
+ break;
+ }
+
+ case 'V': {
+ y = s[1];
+
+ return [s];
+ }
+
+ case 'H': {
+ x = s[1];
+
+ return [s];
+ }
+
+ case 'C': {
+ x = s[5];
+ y = s[6];
+
+ return [s];
+ }
+
+ case 'Q': {
+ x = s[3];
+ y = s[4];
+
+ return [s];
+ }
+
+ default:
+ throw new Error('Unexpected command: ' + s[0]);
+ }
+
+ const nameUC = name.toUpperCase();
+ let isRelative;
+
+ // First command MUST be M|m, it's safe to skip.
+ // Protect from access to [-1] for sure.
+ if (!i) {
+ continue;
+ }
+
+ if (nameUC === 'T') {
+ // quadratic curve
+ isRelative = name === 't';
+
+ const prevSegment = newSegments[i - 1];
+
+ if (prevSegment[0] === 'Q') {
+ prevControlX = prevSegment[1] - x;
+ prevControlY = prevSegment[2] - y;
+ } else if (prevSegment[0] === 'q') {
+ prevControlX = prevSegment[1] - prevSegment[3];
+ prevControlY = prevSegment[2] - prevSegment[4];
+ } else {
+ prevControlX = 0;
+ prevControlY = 0;
+ }
+
+ curControlX = -prevControlX;
+ curControlY = -prevControlY;
+
+ if (!isRelative) {
+ curControlX += x;
+ curControlY += y;
+ }
+
+ newSegments[i] = [
+ isRelative ? 'q' : 'Q',
+ curControlX,
+ curControlY,
+ s[1],
+ s[2],
+ ];
+ } else if (nameUC === 'S') {
+ // cubic curve
+ isRelative = name === 's';
+
+ const prevSegment = newSegments[i - 1];
+
+ if (prevSegment[0] === 'C') {
+ prevControlX = prevSegment[3] - x;
+ prevControlY = prevSegment[4] - y;
+ } else if (prevSegment[0] === 'c') {
+ prevControlX = prevSegment[3] - prevSegment[5];
+ prevControlY = prevSegment[4] - prevSegment[6];
+ } else {
+ prevControlX = 0;
+ prevControlY = 0;
+ }
+
+ curControlX = -prevControlX;
+ curControlY = -prevControlY;
+
+ if (!isRelative) {
+ curControlX += x;
+ curControlY += y;
+ }
+
+ newSegments[i] = [
+ isRelative ? 'c' : 'C',
+ curControlX,
+ curControlY,
+ s[1],
+ s[2],
+ s[3],
+ s[4],
+ ];
+ }
+ }
+
+ return newSegments;
+};