UNPKG

@liammartens/svg-path-properties

Version:

Calculate the length for an SVG path, to use it with node or a Canvas element

72 lines (71 loc) 3.14 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Bezier = void 0; const bezier_functions_1 = require("./bezier-functions"); class Bezier { constructor(ax, ay, bx, by, cx, cy, dx, dy) { this.getTotalLength = () => { return this.length; }; this.getPointAtLength = (length) => { const xs = [this.a.x, this.b.x, this.c.x, this.d.x]; const xy = [this.a.y, this.b.y, this.c.y, this.d.y]; const t = (0, bezier_functions_1.t2length)(length, this.length, i => this.getArcLength(xs, xy, i)); return this.getPoint(xs, xy, t); }; this.getTangentAtLength = (length) => { const xs = [this.a.x, this.b.x, this.c.x, this.d.x]; const xy = [this.a.y, this.b.y, this.c.y, this.d.y]; const t = (0, bezier_functions_1.t2length)(length, this.length, i => this.getArcLength(xs, xy, i)); const derivative = this.getDerivative(xs, xy, t); const mdl = Math.sqrt(derivative.x * derivative.x + derivative.y * derivative.y); let tangent; if (mdl > 0) { tangent = { x: derivative.x / mdl, y: derivative.y / mdl }; } else { tangent = { x: 0, y: 0 }; } return tangent; }; this.getPropertiesAtLength = (length) => { const xs = [this.a.x, this.b.x, this.c.x, this.d.x]; const xy = [this.a.y, this.b.y, this.c.y, this.d.y]; const t = (0, bezier_functions_1.t2length)(length, this.length, i => this.getArcLength(xs, xy, i)); const derivative = this.getDerivative(xs, xy, t); const mdl = Math.sqrt(derivative.x * derivative.x + derivative.y * derivative.y); let tangent; if (mdl > 0) { tangent = { x: derivative.x / mdl, y: derivative.y / mdl }; } else { tangent = { x: 0, y: 0 }; } const point = this.getPoint(xs, xy, t); return { x: point.x, y: point.y, tangentX: tangent.x, tangentY: tangent.y }; }; this.getC = () => { return this.c; }; this.getD = () => { return this.d; }; this.a = { x: ax, y: ay }; this.b = { x: bx, y: by }; this.c = { x: cx, y: cy }; if (dx !== undefined && dy !== undefined) { this.getArcLength = bezier_functions_1.getCubicArcLength; this.getPoint = bezier_functions_1.cubicPoint; this.getDerivative = bezier_functions_1.cubicDerivative; this.d = { x: dx, y: dy }; } else { this.getArcLength = bezier_functions_1.getQuadraticArcLength; this.getPoint = bezier_functions_1.quadraticPoint; this.getDerivative = bezier_functions_1.quadraticDerivative; this.d = { x: 0, y: 0 }; } this.length = this.getArcLength([this.a.x, this.b.x, this.c.x, this.d.x], [this.a.y, this.b.y, this.c.y, this.d.y], 1); } } exports.Bezier = Bezier;