UNPKG

toosoon-utils

Version:
1,955 lines (1,299 loc) 57.4 kB
# TOOSOON UTILS Utility functions & classes. [![NPM](https://nodei.co/npm/toosoon-utils.png)](https://nodei.co/npm/toosoon-utils/) ## Installation Yarn: ```properties $ yarn add toosoon-utils ``` NPM: ```properties $ npm install toosoon-utils ``` ## Usage ```ts import { lerp } from 'toosoon-utils/maths'; console.log(lerp(0.5, 0, 5)); // 2.5 ``` ## Utility functions ### Colors ##### normalizeHexString(hex) Normalize an hexadecimal string. - `hex`: Hexadecimal string. ```ts normalizeHexString(hex: string): string; ``` ##### rgbToHex(rgb) Convert RGB to hexadecimal. - `rgb`: RGB color. ```ts rgbToHex([r, g, b]: [number, number, number]): number; ``` ##### rgbToHexString(rgb) Convert RGB to hexadecimal string. - `rgb`: RGB color. ```ts rgbToHexString([r, g, b]: [number, number, number]): string; ``` ##### hexToRgb(hex) Convert hexadecimal to RGB. - `hex`: Hexadecimal color. ```ts hexToRgb(hex: number | string): [number, number, number]; ``` ##### lighten(hex, amount) Lighten a color. - `hex`: Hexadecimal color. - `[amount=0]`: Amount of the color offset. ```ts lighten(hex: string, amount?: number): string; ``` ##### darken(hex, amount) Darken a color. - `hex`: Hexadecimal color. - `[amount=0]`: Amount of the color offset. ```ts darken(hex: string, amount?: number): string; ``` ##### normalizeHslString(hsl) Normalize an HSL string. - `hsl`: HSL string (format: `'hsl(360, 100%, 100%)'`). ```ts normalizeHslString(hsl: string): [number, number, number]; ``` ##### rgbToHsl(rgb) Convert RGB to HSL. - `rgb`: RGB color. ```ts rgbToHsl([r, g, b]: [number, number, number]): [number, number, number]; ``` ##### hslToRgb(hsl) Convert HSL to RGB. - `hsl`: HSL color. ```ts hslToRgb([h, s, l]: [number, number, number]): [number, number, number]; ``` ##### rgbToHsb(rgb) Convert RGB to HSB. - `rgb`: RGB color. ```ts rgbToHsb([r, g, b]: [number, number, number]): [number, number, number]; ``` ##### hsbToRgb(hsb) Convert HSB to RGB. - `hsb`: HSB color. ```ts hsbToRgb([h, s, b]: [number, number, number]): [number, number, number]; ``` ##### labToHcl(lab) Convert LAB to HCL. - `lab`: LAB color. ```ts labToHcl([l, a, b]: [number, number, number]): [number, number, number]; ``` ##### hclToLab(hcl) Convert HCL to LAB. - `hcl`: HCL color. ```ts hclToLab([h, c, l]: [number, number, number]): [number, number, number]; ``` ##### labToRgb(lab) Convert LAB to RGB. - `lab`: LAB color. ```ts labToRgb([l, a, b]: [number, number, number]): [number, number, number]; ``` ##### rgbToLab(rgb) Convert RGB to LAB. - `rgb`: RGB color. ```ts rgbToLab([r, g, b]: [number, number, number]): [number, number, number]; ``` ##### deltaE(labA, labB) Get the delta from two LAB colors. - `labA`: First LAB color. - `labB`: Second LAB color. ```ts deltaE(labA: [number, number, number], labB: [number, number, number]): number; ``` ##### rgbToHcl(rgb) Convert RGB to HCL. - `rgb`: RGB color. ```ts rgbToHcl([r, g, b]: [number, number, number]): [number, number, number]; ``` ##### hclToRgb(hcl) Convert HCL to RGB. - `hcl`: HCL color. ```ts hclToRgb([h, c, l]: [number, number, number]): [number, number, number]; ``` ### DOM ##### closest(element, selector) Find the closest parent that matches a selector. - `element`: Target element. - `selector`: Selector or parent to match. ```ts closest(element: Element | null, selector: Element | string): Element | null; ``` ##### createCanvas(width, height) Create a canvas and 2d context. - `width`: Width of the canvas. - `height`: Height of the canvas. ```ts createCanvas(width: number, height: number): { canvas: HTMLCanvasElement; ctx: CanvasRenderingContext2D }; ``` ##### injectStyles(styles) Inject CSS styles in `document.head`. - `styles`: CSS styles to inject. ```ts injectStyles(styles: string): void; ``` ### Files ##### download(blob, filename) Download a Blob object into user files. - `blob`: Blob object to download. - `filename`: Downloaded file name. ```ts download(blob: Blob, filename: string): void; ``` ##### upload(onLoad) Upload a file from user files. - `onLoad`: Callback called once the file is loaded. - `[accept='']` MIME type the file input should accept. ```ts upload(onLoad: (dataUrl: string) => void, accept?: string): void; ``` ### Functions ##### noop() No-op function. ```ts noop(): void; ``` ##### wait(delay) Promise wrapped setTimeout. - `[delay=0]`: Time to wait (in milliseconds). ```ts wait(delay?: number): Promise<void>; ``` ##### isDefined(value) Check if a value is defined. - `value`: Value to check. ```ts isDefined(value: any): boolean; ``` ##### debounce(callback, delay) Create a debounced function that delays the execution of `callback` until a specified `delay` time has passed since the last call. - `callback`: Function to debounce. - `delay`: Delay (in milliseconds). ```ts debounce(callback: Function, delay: number): Function; ``` ##### throttle(callback, limit) Create a throttled function that limits the execution of `callback` to once every `limit` time. - `callback`: Function to throttle. - `limit`: Minimum interval between two calls (in milliseconds). ```ts throttle(callback: Function, limit: number): Function; ``` ##### defer() Deferred promise implementation. ```ts defer<T>(): Deferred<T>; ``` ##### now() Polyfill for `now()` functions. ```ts now(): number; ``` ### Geometry ##### toDegrees(radians) Convert a radians value into degrees. - `radians`: Angle in radians. ```ts toDegrees(radians: number): number; ``` ##### toRadians(degrees) Convert a degrees value into radians. - `degrees`: Angle in degrees. ```ts toRadians(degrees: number): number; ``` ##### angle(x1, y1, x2, y2) Calculate the angle from a point to another. - `x1`: X value of the first point. - `y1`: Y value of the first point. - `x2`: X value of the second point. - `y2`: Y value of the second point. ```ts angle(x1: number, y1: number, x2: number, y2: number): number; ``` ##### closestAngle(source, target) Find the closest angle between to angles. - `source`: Source angle (in radians). - `target`: Target angle (in radians). ```ts closestAngle(source: number, target: number): number; ``` ##### distance(x1, y1, x2, y2) Calculate the distance between two points. - `x1`: X-axis coordinate of the first point. - `y1`: Y-axis coordinate of the first point. - `x2`: X-axis coordinate of the second point. - `y2`: Y-axis coordinate of the second point. ```ts distance(x1: number, y1: number, x2: number, y2: number): number; ``` ##### dot(x1, y1, x2, y2) Calculate the dot product of two vectors. - `x1`: X-axis coordinate of the first vector. - `y1`: Y-axis coordinate of the first vector. - `x2`: X-axis coordinate of the second vector. - `y2`: Y-axis coordinate of the second vector. ```ts dot(x1: number, y1: number, x2: number, y2: number): number; ``` ##### cross(x1, y1, x2, y2) Calculate the cross product of two vectors. - `x1`: X-axis coordinate of the first vector. - `y1`: Y-axis coordinate of the first vector. - `x2`: X-axis coordinate of the second vector. - `y2`: Y-axis coordinate of the second vector. ```ts cross(x1: number, y1: number, x2: number, y2: number): number; ``` ##### diagonal(width, height) Calculate the length of the diagonal of a rectangle. - `width`: Width of the rectangle. - `height`: Height of the rectangle. ```ts diagonal(width: number, height: number): number; ``` ##### radToSphere(radius, phi, theta) Convert radians to a 3D point on the surface of a unit sphere. - `radius`: Radius of the sphere. - `phi`: Polar angle from the y (up) axis [0, PI]. - `theta`: Equator angle around the y (up) axis [0, 2*PI]. - `[target]`: Target vector. ```ts radToSphere(radius: number, phi: number, theta: number, target?: [number, number, number]): [number, number, number]; ``` #### Curves ##### line(t, x1, y1, x2, y2) Interpolate a point on line. - `t`: Normalized time value to interpolate. - `x1`: X-axis coordinate of the start point. - `y1`: Y-axis coordinate of the start point. - `x2`: X-axis coordinate of the end point. - `y2`: Y-axis coordinate of the end point. ```ts line( t: number, x1: number, y1: number, x2: number, y2: number ): [number, number]; ``` ##### quadraticBezier(t, x1, y1, cpx, cpy, x2, y2) Interpolate a point on Quadratic Bézier curve. - `t`: Normalized time value to interpolate. - `x1`: X-axis coordinate of the start point. - `y1`: Y-axis coordinate of the start point. - `cpx`: X-axis coordinate of the control point. - `cpy`: Y-axis coordinate of the control point. - `x2`: X-axis coordinate of the end point. - `y2`: Y-axis coordinate of the end point. ```ts quadraticBezier( t: number, x1: number, y1: number, cpx: number, cpy: number, x2: number, y2: number ): [number, number]; ``` ##### cubicBezier(t, x1, y1, cp1x, cp1y, cp2x, cp2y, x2, y2) Interpolate a point on Cubic Bézier curve. - `t`: Normalized time value to interpolate. - `x1`: X-axis coordinate of the start point. - `y1`: Y-axis coordinate of the start point. - `cp1x`: X-axis coordinate of the first control point. - `cp1y`: Y-axis coordinate of the first control point. - `cp2x`: X-axis coordinate of the second control point. - `cp2y`: Y-axis coordinate of the second control point. - `x2`: X-axis coordinate of the end point. - `y2`: Y-axis coordinate of the end point. ```ts cubicBezier( t: number, x1: number, y1: number, cp1x: number, cp1y: number, cp2x: number, cp2y: number, x2: number, y2: number ): [number, number]; ``` ##### catmullRom(t, x1, y1, cp1x, cpy1, cp2x, cp2y, x2, y2) Interpolate a point on a Catmull-Rom spline. - `t`: Normalized time value to interpolate. - `x1`: X-axis coordinate of the start point. - `y1`: Y-axis coordinate of the start point. - `cp1x`: X-axis coordinate of the first control point. - `cp1y`: Y-axis coordinate of the first control point. - `cp2x`: X-axis coordinate of the second control point. - `cp2y`: Y-axis coordinate of the second control point. - `x2`: X-axis coordinate of the end point. - `y2`: Y-axis coordinate of the end point. ```ts catmullRom( t: number, x1: number, y1: number, cp1x: number, cp1y: number, cp2x: number, cp2y: number, x2: number, y2: number ): [number, number]; ``` ##### ellipse(t, cx, cy, rx, ry, rotation, startAngle, endAngle, counterclockwise) Interpolate a point on an elliptical arc. - `t`: Normalized time value to interpolate. - `cx`: X-axis coordinate of the center of the ellipse. - `cy`: Y-axis coordinate of the center of the ellipse. - `rx`: X-radius of the ellipse. - `ry`: Y-radius of the ellipse. - `[rotation=0]`: Rotation angle of the ellipse (in radians), counterclockwise from the positive X-axis. - `[startAngle=0]`: Start angle of the arc (in radians). - `[endAngle=TWO_PI]`: Rotation angle of the arc (in radians). - `[counterclockwise=false]`: Flag indicating the direction of the arc. ```ts ellipse( t: number, cx: number, cy: number, rx: number, ry: number, rotation?: number, startAngle?: number, endAngle?: number, counterclockwise?: boolean ): [number, number]; ``` ##### arc(t, cx, cy, radius, startAngle, endAngle, counterclockwise) Interpolate a point on a circular arc. - `t`: Normalized time value to interpolate. - `cx`: X-axis coordinate of the center of the circle. - `cy`: Y-axis coordinate of the center of the circle. - `radius`: Radius of the circle. - `[startAngle]`: Start angle of the arc (in radians). - `[endAngle]`: End angle of the arc (in radians). - `[counterclockwise=false]`: Flag indicating the direction of the arc. ```ts arc( t: number, cx: number, cy: number, radius: number, startAngle?: number, endAngle?: number, counterclockwise?: boolean ): [number, number]; ``` ##### isCoincident(x1, y1, x2, y2) Check if two points are coincident. - `x1`: X-axis coordinate of the first point. - `y1`: Y-axis coordinate of the first point. - `x2`: X-axis coordinate of the second point. - `y2`: Y-axis coordinate of the second point. ```ts isCoincident(x1: number, y1: number, x2: number, y2: number): boolean; ``` ##### isCollinear(x1, y1, x2, y2, x3, y3) Check if 3 points are collinear. - `x1`: X-axis coordinate of the first point. - `y1`: Y-axis coordinate of the first point. - `x2`: X-axis coordinate of the second point. - `y2`: Y-axis coordinate of the second point. - `x3`: Y-axis coordinate of the third point. - `y3`: Y-axis coordinate of the third point. ```ts isCollinear(x1: number, y1: number, x2: number, y2: number, x3: number, y3: number): boolean; ``` #### Fit ```ts type FitInput = { width: number; height: number; }; type FitOutput = { left: number; top: number; width: number; height: number; scale: number; }; ``` ##### cover(target, container) Make a target fit a container (cover mode). - `target`: Dimension of the target. - `container`: Dimension of the container. ```ts cover(target: FitInput, container: FitInput): FitOutput; ``` ##### contain(target, container) Make a target fit a container (contain mode). - `target`: Dimension of the target. - `container`: Dimension of the container. ```ts contain(target: FitInput, container: FitInput): FitOutput; ``` ### Maths ##### isEven(value) Check if a number is even. - `value`: Value to check. ```ts isEven(value: number): boolean; ``` ##### isOdd(value) Check if a number is odd. - `value`: Value to check. ```ts isOdd(value: number): boolean; ``` ##### isPowerOf2(value) Check if a number is a power of 2. - `value`: Value to check. ```ts isPowerOf2(value: number): boolean; ``` ##### toPowerOf2(value) Find closest power of 2 that fits a number. - `value`: Incoming value. - `[mode='ceil']`: Can be `'floor'`, `'ceil'` or `'round'`. ```ts toPowerOf2(value: number, mode?: string): number; ``` ##### sign(value) Return the sign (positive or negative) of a number. - `value`: Value to check. ```ts sign(value: number): number; ``` ##### clamp(value, min, max) Clamp a value between two bounds. - `value`: Value to clamp. - `[min=0]`: Minimum boundary. - `[max=1]`: Maximum boundary. ```ts clamp(value: number, min?: number, max?: number): number; ``` ##### lerp(t, min, max) Linear interpolation between two values (lerping). - `t`: Normalized time value to interpolate. - `min`: Minimum value. - `max`: Maximum value. ```ts lerp(t: number, min: number, max: number): number; ``` ##### triLerp(t, min, max, target) Triangular interpolation between two values. - `t`: Normalized time value to interpolate. - `min`: Minimum value. - `max`: Maximum value. - `target`: Triangle target value. ```ts triLerp(t: number, min: number, max: number, target: number): number; ``` ##### expLerp(t, currentMin, currentMax, targetMin, targetMax) Exponential interpolation between two values. - `t`: Normalized time value to interpolate. - `currentMin`: Lower bound of the value's current range. - `currentMax`: Upper bound of the value's current range. - `targetMin`: Lower bound of the value's target range. - `targetMax`: Upper bound of the value's target range. ```ts expLerp(t: number, currentMin: number, currentMax: number, targetMin: number, targetMax: number): number; ``` ##### normalize(value, min, max) Normalize a value between two bounds. - `value`: Value to normalize. - `min`: Minimum boundary. - `max`: Maximum boundary. ```ts normalize(value: number, min: number, max: number): number; ``` ##### map(value, currentMin, currentMax, targetMin, targetMax) Re-map a number from one range to another. - `value`: Value to re-map. - `currentMin`: Lower bound of the value's current range. - `currentMax`: Upper bound of the value's current range. - `targetMin`: Lower bound of the value's target range. - `targetMax`: Upper bound of the value's target range. ```ts map(value: number, currentMin: number, currentMax: number, targetMin: number, targetMax: number): number; ``` ##### snap(value, multiple) Round a number up to a nearest multiple. - `value`: Value to round. - `[multiple=1]`: Multiple to round to. ```ts snap(value: number, multiple?: number): number; ``` ##### modAbs(value, length) Modulo absolute a value based on a length. - `value`: Value to modulate. - `length`: Total length. ```ts modAbs(value: number, length: number): number; ``` ##### pingPong(value, length) Move back and forth a value between 0 and length, so that it is never larger than length and never smaller than 0. - `value`: Value to modulate. - `length`: Total length. ```ts pingPong(value: number, length: number): number; ``` ##### smoothstep(value, min, max) Smooth a value using cubic Hermite interpolation. - `value`: Value to smooth. - `[min=0]`: Minimum boundary. - `[max=1]`: Maximum boundary. ```ts smoothstep(value: number, min?: number, max?: number): number; ``` ##### parabola(x, power) Re-map the [0, 1] interval into [0, 1] parabola, such that corners are remaped to 0 and the center to 1. - `x`: Normalized coordinate on X axis. - `[power=1]`: Parabola power. ```ts parabola(x: number, power?: number): number; ``` ##### sum(array) Return the sum of numbers. - `array`: Array of numbers. ```ts sum(array: number[]): number; ``` ##### average(array) Return the average of numbers. - `array`: Array of numbers. ```ts average(array: number[]): number; ``` ##### damp(value, target, damping, delta) Smoothly interpolate a number toward another. - `value`: Value to interpolate. - `target`: Destination of the interpolation. - `damping`: A higher value will make the movement more sudden, and a lower value will make the movement more gradual. - `delta`: Delta time (in seconds). ```ts damp(value: number, target: number, damping: number, delta: number): number; ``` ### Random ##### randomBoolean(probability) Generate a random boolean (true or false). - `[probability=0.5]`: Probability to get true. ```ts randomBoolean(probability?: number): boolean; ``` ##### randomSign(probability) Generate a random sign (1 or -1). - `[probability=0.5]`: Probability to get 1. ```ts randomSign(probability?: number): number; ``` ##### randomFloat(min, max) Generate a random floating-point number within a specified range. - `[min=0]`: Minimum boundary. - `[max=1]`: Maximum boundary. - `[precision=2]`: Number of digits after the decimal point. ```ts randomFloat(min?: number, max?: number, precision?: number): number; ``` ##### randomInt(min, max) Generate a random integer number within a specified range. - `min`: Minimum boundary. - `max`: Maximum boundary. ```ts randomInt(min: number, max: number): number; ``` ##### randomHexColor() Generate a random hexadecimal color. ```ts randomHexColor(): string; ``` ##### randomItem(array) Pick a random item from a given array. - `array`: Array to pick the item from. ```ts randomItem<T>(array: T[]): T | undefined; ``` ##### randomObjectProperty(object) Pick a random property value from a given object. - `object`: Object to pick the property from. ```ts randomObjectProperty<T>(object: Record<string, T>): T | undefined; ``` ##### randomIndex(weights) Select a random index from an array of weighted items. - `weights`: Array of weights. ```ts randomIndex(weights: number[]): number; ``` ##### randomGaussian(mean, spread) Generate a random number fitting a Gaussian (normal) distribution. - `[mean=0]`: Central value. - `[spread=1]`: Standard deviation. ```ts randomGaussian(mean?: number, spread?: number): number; ``` ##### onCircle(radius) Produce a random 2D point around the perimiter of a unit circle. - `[radius=1]`: Radius of the circle. - `[target]`: Target vector. ```ts onCircle(radius?: number, target?: [number, number]): [number, number]; ``` ##### insideCircle(radius) Produce a random 2D point inside a unit circle. - `[radius=1]`: Radius of the circle. - `[target]` Target vector. ```ts insideCircle(radius?: number, target?: [number, number]): [number, number]; ``` ##### onSphere(radius) Produce a random 3D point on the surface of a unit sphere. - `[radius=1]`: Radius of the sphere. - `[target]`: Target vector. ```ts onSphere(radius?: number, target?: [number, number, number]): [number, number, number]; ``` ##### insideSphere(radius) Produce a random 3D point inside a unit sphere. - `[radius=1]`: Radius of the sphere. - `[target]`: Target vector. ```ts insideSphere(radius?: number, target?: [number, number, number]): [number, number, number]; ``` ### Pseudo-Random Number Generator (PRNG) #### PRNG Algorithms **Credits**: [Seeding random number generator](https://stackoverflow.com/questions/521295/seeding-the-random-number-generator-in-javascript) ##### cyrb128(seed) Produce a 128-bit hash value from a string. `seed`: Initial seed state. ```ts cyrb128(prng: string | object): [number, number, number, number]; ``` ##### sfc32(a, b, c, d) _Simple Fast Counter_, Generator with a 128-bit state. ```ts sfc32(a: number, b: number, c: number, d: number): number; ``` ##### splitmix32(a) _SplitMix32_, Generator with a 32-bit state. ```ts splitmix32(a: number): number; ``` ##### mulberry32(a) _Mulberry32_, Generator with a 32-bit state. ```ts mulberry32(a: number): number; ``` ##### jsf32(a, b, c, d) _Jenkins' Small Fast_, Generator with a 32-bit state. ```ts jsf32(a: number, b: number, c: number, d: number): number; ``` ##### xoshiro128ss(a, b, c, d) _xoshiro128\*\*_, Generator with a 128-bit state. ```ts xoshiro128ss(a: number, b: number, c: number, d: number): number; ``` #### PRNG functions Thanks to the above algorithms, a seed-based version of most of the [random functions](#random) exist with additionnal parameters for a `seed` string and a PRNG `algorithm` function. PRNG parameters: ```ts type PRNGParameters = string | { seed: string; algorithm: (...args: number[]) => number }; ``` ##### random(prng) Generate a pseudo-random number in the interval [0, 1]. It is the PRNG equivalent of `Math.random()`. - `prng`: PRNG parameters. ```ts random(prng: PRNGParameters): number; ``` ##### randomBoolean(prng) Generate a pseudo-random boolean (true or false). - `prng`: PRNG parameters. - `[probability=0.5]`: Probability to get true. ```ts randomBoolean(prng: PRNGParameters, probability?: number): boolean; ``` ##### randomSign(prng) Generate a pseudo-random sign (1 or -1). - `prng`: PRNG parameters. - `[probability=0.5]`: Probability to get 1. ```ts randomSign(prng: PRNGParameters, probability?: number): number; ``` ##### randomFloat(prng, min, max) Generate a pseudo-random floating-point number within a specified range. - `prng`: PRNG parameters. - `[min=0]`: Minimum boundary. - `[max=1]`: Maximum boundary. - `[precision=2]`: Number of digits after the decimal point. ```ts randomFloat(prng: PRNGParameters, min?: number, max?: number, precision?: number): number; ``` ##### randomInt(prng, min, max) Generate a pseudo-random integer number within a specified range. - `prng`: PRNG parameters. - `min`: Minimum boundary. - `max`: Maximum boundary. ```ts randomInt(prng: PRNGParameters, min: number, max: number): number; ``` ##### randomHexColor(prng) Generate a pseudo-random hexadecimal color. - `prng`: PRNG parameters. ```ts randomHexColor(prng: PRNGParameters): string; ``` ##### randomItem(prng, array) Pick a pseudo-random item from a given array. - `prng`: PRNG parameters. - `array`: Array to pick the item from. ```ts randomItem<T>(prng: PRNGParameters, array: T[]): T | undefined; ``` ##### randomObjectProperty(prng) Pick a pseudo-random property value from a given object. - `prng`: PRNG parameters. - `object`: Object to pick the property from. ```ts randomObjectProperty<T>(prng: PRNGParameters, object: Record<string, T>): T | undefined; ``` ##### randomIndex(prng) Select a pseudo-random index from an array of weighted items. - `prng`: PRNG parameters. - `weights`: Array of weights. ```ts randomIndex(prng: string | object, weights: number[]): number; ``` ##### randomGaussian(prng, mean, spread) Generate a pseudo-random number fitting a Gaussian (normal) distribution. - `prng`: PRNG parameters. - `[mean=0]`: Central value. - `[spread=1]`: Standard deviation. ```ts randomGaussian(prng: string | object, mean?: number, spread?: number): number; ``` ### Query parameters ##### getQuery(property) Get a query parameter. - `property`: Query property to check. ```ts getQuery(property: string): string | null; ``` ##### setQuery(property) Set a query parameter. - `property`: Query property to set. - `value`: Value to set. ```ts setQuery(property: string, value: string): void; ``` ##### hasQuery(property) Check if a query parameter exists. - `property`: Query property to check. ```ts hasQuery(property: string): boolean; ``` ### Strings #### Cases ##### capitalize(string) Capitalize a string. - `string`: String to capitalize. ```ts capitalize(string: string): string; ``` ##### toKebabCase(string) Convert a string to kebab-case: 'Hello world' -> 'hello-world'. - `string`: String to convert. ```ts toKebabCase(string: string): string; ``` ##### toSnakeCase(string) Convert a string to snake_case: 'Hello world' -> 'hello_world'. - `string`: String to convert. ```ts toSnakeCase(string: string): string; ``` ##### toCamelCase(string) Convert a string to camelCase: 'Hello world' -> 'helloWorld'. - `string`: String to convert. ```ts toCamelCase(string: string): string; ``` ##### toPascalCase(string) Convert a string to PascalCase: 'Hello world' -> 'HelloWorld'. - `string`: String to convert. ```ts toPascalCase(string: string): string; ``` ##### toTrainCase(string) Convert a string to Train-Case: 'Hello world' -> 'Hello-World'. - `string`: String to convert. ```ts toTrainCase(string: string): string; ``` ##### toConstantCase(string) Convert a string to CONSTANT_CASE: 'Hello world' -> 'HELLO_WORLD'. - `string`: String to convert. ```ts toConstantCase(string: string): string; ``` #### Paths ##### cleanPath(path) Clean a path by removing its parameters. - `path`: Path to clean. ```ts cleanPath(path: string): string; ``` ##### addTrailingSlash(path) Convert a path by ensuring it has a trailing slash. - `path`: Path to convert. ```ts addTrailingSlash(path: string): string; ``` ##### removeTrailingSlash(path) Convert a path by ensuring it has not a trailing slash. - `path`: Path to convert. ```ts removeTrailingSlash(path: string): string; ``` ## Utility classes Utility classes for manipulating curves. ### Curve <a id="curve"></a> Utility abstract class for manipulating curves. - [new Curve()](#curve) - .isCurve: `true` - [.arcLengthDivisions](#curve-arc-length-divisions): `number` - [.needsUpdate](#curve-needs-update): `boolean` - [.getPoint(t)](#curve-get-point-method): `[number, number]` - [.getPointAt(u)](#curve-get-point-at-method): `[number, number]` - [.getPoints(divisions)](#curve-get-points-method): `Array<[number, number]>` - [.getSpacedPoints(divisions)](#curve-get-spaced-points-method): `Array<[number, number]>` - [.getLengths()](#curve-get-length-method): `number` - [.getLengths()](#curve-get-lengths-method): `number[]` - [.updateArcLengths()](#curve-update-arc-lengths-method): `void` - [.getUtoTmapping(t, targetArcLength)](#curve-get-u-to-t-mapping-method): `number` - [.getTangent(t)](#curve-get-tangent-method): `[number, number]` - [.getTangentAt(u)](#curve-get-tangent-at-method): `[number, number]` - `static` [.isClosed(points)](#curve-static-is-closed-method): `boolean` #### Properties ##### arcLengthDivisions <a id="curve-arc-length-divisions"></a> Amount of divisions when calculating the cumulative segment lengths of a curve. ```ts Curve.arcLengthDivisions: number; ``` ##### needsUpdate <a id="curve-needs-update"></a> Must be set to `true` if the curve parameters have changed. ```ts Curve.needsUpdate: boolean; ``` #### Methods ##### getPoint(t) <a id="curve-get-point-method"></a> Interpolate a point on the curve. - `u`: Normalized time value to interpolate. ```ts Curve.getPoint(t: number): [number, number]; ``` ##### getPointAt(u) <a id="curve-get-point-at-method"></a> Interpolate a point on the curve. - `u`: Normalized position value to interpolate. ```ts Curve.getPointAt(u: number): [number, number]; ``` ##### getPoints(divisions) <a id="curve-get-points-method"></a> Compute the curve shape into an array of points. - `[divisions=5]`: Number of divisions. ```ts Curve.getPoints(divisions?: number): Array<[number, number]>; ``` ##### getSpacedPoints(divisions) <a id="curve-get-spaced-points-method"></a> Compute the curve shape into an array of equi-spaced points across the entire curve. - `[divisions=5]`: Number of divisions. ```ts Curve.getSpacedPoints(divisions?: number): Array<[number, number]>; ``` ##### getLength() <a id="curve-get-lengt-methodh"></a> Compute the total arc length of the curve. ```ts Curve.getLength(): number; ``` ##### getLengths() <a id="curve-get-lengths-method"></a> Compute the cumulative segment lengths of the curve. - `[divisions]`: Number of divisions. ```ts Curve.getLengths(divisions?: number): number[]; ``` ##### updateArcLengths() <a id="curve-get-point-method"></a> Update the cached cumulative segment lengths. ```ts Curve.updateArcLengths(): void; ``` ##### getUtoTmapping(t, targetArcLength) <a id="curve-get-u-to-t)mapping-method"></a> Re-map a normalized position value into normalized time. - `u`: Normalized position value to interpolate. - `[targetArcLength]`: Distance on the curve. ```ts Curve.getUtoTmapping(u: number, targetArcLength?: number): number; ``` ##### getTangent(t) <a id="curve-get-tangent-method"></a> Compute an unit vector tangent for the given normalized time value. - `t`: Normalized time value. ```ts Curve.getTangent(t: number): [number, number]; ``` ##### getTangentAt(u) <a id="curve-get-tangent-at-method"></a> Compute an unit vector tangent for the given normalized position value. - `u`: Normalized position value. ```ts Curve.getTangentAt(u: number): [number, number]; ``` ##### `static` isClosed(points) <a id="curve-static-is-closed-method"></a> Static method to check if given points are defining a closed curve. - `points`: Points to check. ```ts static Curve.isClosed(points: Array<[number, number]>): boolean; ``` ### LineCurve <a id="line-curve"></a> Utility class extending [Curve](#curve) for manipulating lines. - [new LineCurve(x1, y1, x2, y2)](#line-curve) | Parameter | Type | Default | Description | | --------- | -------- | ------- | ------------------------------------- | | x1 | `number` | | X-axis coordinate of the start point. | | y1 | `number` | | Y-axis coordinate of the start point. | | x2 | `number` | | X-axis coordinate of the end point. | | y2 | `number` | | Y-axis coordinate of the end point. | ### PolylineCurve <a id="polyline-curve"></a> Utility class extending [Curve](#curve) for manipulating polylines. - [new PolylineCurve(points)](#polyline-curve) | Parameter | Type | Default | Description | | --------- | ------------------------- | ------- | ----------------------------------- | | [points] | `Array<[number, number]>` | `[]` | Array of points defining the curve. | ### QuadraticBezierCurve <a id="quadratic-bezier-curve"></a> Utility class extending [Curve](#curve) for manipulating Quadratic Bézier curves. - [new QuadraticBezierCurve(x1, y1, cpx, cpy, x2, y2)](#quadratic-bezier-curve) | Parameter | Type | Default | Description | | --------- | -------- | ------- | --------------------------------------- | | x1 | `number` | | X-axis coordinate of the start point. | | y1 | `number` | | Y-axis coordinate of the start point. | | cpx | `number` | | X-axis coordinate of the control point. | | cpy | `number` | | Y-axis coordinate of the control point. | | x2 | `number` | | X-axis coordinate of the end point. | | y2 | `number` | | Y-axis coordinate of the end point. | ### CubicBezierCurve <a id="cubic-bezier-curve"></a> Utility class extending [Curve](#curve) for manipulating Cubic Bézier curves. - [new CubicBezierCurve(x1, y1, cp1x, cp1y, cp2x, cp2y x2, y2)](#cubic-bezier-curve) | Parameter | Type | Default | Description | | --------- | -------- | ------- | ---------------------------------------------- | | x1 | `number` | | X-axis coordinate of the start point. | | y1 | `number` | | Y-axis coordinate of the start point. | | cp1x | `number` | | X-axis coordinate of the first control point. | | cp1y | `number` | | Y-axis coordinate of the first control point. | | cp2x | `number` | | X-axis coordinate of the second control point. | | cp2y | `number` | | Y-axis coordinate of the second control point. | | x2 | `number` | | X-axis coordinate of the end point. | | y2 | `number` | | Y-axis coordinate of the end point. | ### CatmullRomCurve <a id="catmull-rom-curve"></a> Utility class extending [Curve](#curve) for manipulating Catmull-Rom curves. - [new CatmullRomCurve(x1, y1, cp1x, cp1y, cp2x, cp2y x2, y2)](#catmull-rom-bezier-curve) | Parameter | Type | Default | Description | | --------- | -------- | ------- | ---------------------------------------------- | | x1 | `number` | | X-axis coordinate of the start point. | | y1 | `number` | | Y-axis coordinate of the start point. | | cp1x | `number` | | X-axis coordinate of the first control point. | | cp1y | `number` | | Y-axis coordinate of the first control point. | | cp2x | `number` | | X-axis coordinate of the second control point. | | cp2y | `number` | | Y-axis coordinate of the second control point. | | x2 | `number` | | X-axis coordinate of the end point. | | y2 | `number` | | Y-axis coordinate of the end point. | ### SplineCurve <a id="spline-curve"></a> Utility class extending [Curve](#curve) for manipulating splines. - [new SplineCurve(points)](#spline-curve) | Parameter | Type | Default | Description | | --------- | ------------------------- | ------- | ----------------------------------- | | [points] | `Array<[number, number]>` | `[]` | Array of points defining the curve. | ### EllipseCurve <a id="ellipse-curve"></a> Utility class extending [Curve](#curve) for manipulating ellipses. - [new EllipseCurve(cx, cy, rx, ry, rotation, startAngle, endAngle, counterclockwise)](#ellipse-curve) | Parameter | Type | Default | Description | | ------------------ | --------- | ------- | -------------------------------------------------------------------------------------- | | cx | `number` | | X-axis coordinate of the center of the ellipse. | | cy | `number` | | Y-axis coordinate of the center of the ellipse. | | rx | `number` | | X-radius of the ellipse. | | ry | `number` | | Y-radius of the ellipse. | | [rotation] | `number` | | Rotation angle of the ellipse (in radians), counterclockwise from the positive X-axis. | | [startAngle] | `number` | | Rotation angle of the arc (in radians). | | [endAngle] | `number` | | Rotation angle of the arc (in radians). | | [counterclockwise] | `boolean` | | Flag indicating the direction of the arc. | ### ArcCurve <a id="arc-curve"></a> Utility class extending [Curve](#curve) for manipulating arcs. - [new ArcCurve(cx, cy, radius, startAngle, endAngle, counterclockwise)](#arc-curve) | Parameter | Type | Default | Description | | ------------------ | --------- | ------- | ---------------------------------------------- | | cx | `number` | | X-axis coordinate of the center of the circle. | | cy | `number` | | Y-axis coordinate of the center of the circle. | | radius | `number` | | X-radius of the circle. | | [startAngle] | `number` | | Rotation angle of the arc (in radians). | | [endAngle] | `number` | | Rotation angle of the arc (in radians). | | [counterclockwise] | `boolean` | | Flag indicating the direction of the arc. | ### Path <a id="path"></a> Utility class extending [Curve](#curve) for manipulating connected curves. - [new Path()](#path) - .isPath: `true` - [.curves](#path-curves): `Curve[]` - [.points](#path-points): `Array<[number, number]>` - [.autoClose](#path-auto-close): `boolean` - [.add()](#path-add-method): `void` - [.getCurveLengths()](#path-get-curve-lengths-method): `number[]` #### Properties ##### curves <a id="path-curves"></a> Array of curves composing the path. ```ts Path.curves: Curve[]; ``` ##### points <a id="path-points"></a> Array of points composing the path. ```ts Path.points: Array<[number, number]>; ``` ##### autoClose <a id="path-auto-close"></a> ```ts Path.autoClose: boolean; ``` #### Methods ##### add <a id="path-add-method"></a> Add a curve to this curve path. - `curve`: Curve to add. ```ts Path.add(curve: Curve): void; ``` ##### getCurveLengths <a id="path-get-curve-lengths-method"></a> Compute the cumulative curve lengths of the curve path. ```ts Path.getCurveLengths(): number[]; ``` ### PathContext <a id="path-context"></a> Utility class extending [Path](#path) providing methods similar to the 2D Canvas API. - [new PathContext()](#path-context) - [.currentPosition](#path-context-current-position): `[number, number]` - [.setFromPoints(points)](#path-context-set-from-points-method): `this` - [.beginPath()](#path-context-begin-path-method): `this` - [.closePath()](#path-context-close-path-method): `this` - [.moveTo(x, y)](#path-context-move-to-method): `this` - [.lineTo(x, y)](#path-context-line-to-method): `this` - [.polylineTo(points)](#path-context-polyline-to-method): `this` - [.arcTo(x1, y1, x2, y2, radius)](#path-context-arc-to-method): `this` - [.quadraticCurveTo(cpx, cpy, x2, y2)](#path-context-quadratic-curve-to-method): `this` - [.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x2, y2)](#path-context-bezier-curve-to-method): `this` - [.catmullRomCurveTo(cp1x, cp1y, cp2x, cp2y, x2, y2)](#path-context-catmull-rom-to-method): `this` - [.splineTo(points)](#path-context-spline-to-method): `this` - [.ellipse(cx, cy, rx, ry, rotation, startAngle, endAngle, counterclockwise)](#path-context-ellipse-method): `this` - [.arc(cx, cy, radius, startAngle, endAngle, counterclockwise)](#path-context-arc-method): `this` - [.rect(x, y, width, height)](#path-context-rect-method): `this` - [.roundRect(x, y, width, height, radius)](#path-context-round-rect-method): `this` #### Properties ##### currentPosition <a id="path-context-current-position"></a> Path current offset position. ```ts PathContext.currentPosition: [number, number]; ``` #### Methods ##### setFromPoints(points) <a id="path-context-set-from-points-method"></a> Create a path from the given list of points. - `points`: Array of points defining the path. - `[type]`: Type of curve used for creating the path. ```ts PathContext.setFromPoints(points: Array<[number, number]>, type?: 'lines' | 'polyline' | 'spline'): this; ``` ##### beginPath() <a id="path-context-begin-path-method"></a> Begin the path. Reset `currentPosition`. ```ts PathContext.beginPath(): this; ``` ##### closePath <a id="path-context-close-path-method"></a> Draw a line from the ending position to the beginning position of the path. Add an instance of [LineCurve](#line-curve) to the path. ```ts PathContext.closePath(): this; ``` ##### moveTo(x, y) <a id="path-context-move-to-method"></a> Move `currentPosition` to the coordinates specified by `x` and `y`. - `x`: X-axis coordinate of the point. - `y`: Y-axis coordinate of the point. ```ts PathContext.moveTo(x: number, y: number): this; ``` ##### lineTo(x, y) <a id="path-context-line-to-method"></a> Draw a line from the current position to the position specified by `x` and `y`. Add an instance of [LineCurve](#line-curve) to the path. - `x`: X-axis coordinate of the point. - `y`: Y-axis coordinate of the point. ```ts PathContext.lineTo(x: number, y: number): this; ``` ##### polylineTo(points) <a id="path-context-polyline-to-method"></a> Draw a Polyline curve from the current position through the given points. Add an instance of [PolylineCurve](#polyline-curve) to the path. - `points`: Array of points defining the curve. ```ts PathContext.polylineTo(points: Array<[number, number]>): this; ``` ##### arcTo(x1, y1, x2, y2, radius) <a id="path-context-arc-to-method"></a> Draw an Arc curve from the current position, tangential to the 2 segments created by both control points Add an instance of [ArcCurve](#arc-curve) to the path. - `x1`: X-axis coordinate of the first control point. - `y1`: Y-axis coordinate of the first control point. - `x2`: X-axis coordinate of the second control point. - `y2`: Y-axis coordinate of the second control point. - `radius`: Arc radius (Must be non-negative). ```ts PathContext.arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): this; ``` ##### quadraticCurveTo(cpx, cpy, x2, y2) <a id="path-context-quadratic-curve-to-method"></a> Draw a Quadratic Bézier curve from the current position to the end point specified by `x` and `y`, using the control point specified by `cpx` and `cpy`. Add an instance of [QuadraticBezierCurve](#quadratic-bezier-curve) to the path. - `cpx`: X-axis coordinate of the control point. - `cpy`: Y-axis coordinate of the control point. - `x2`: X-axis coordinate of the end point. - `y2`: Y-axis coordinate of the end point. ```ts PathContext.quadraticCurveTo(cpx: number, cpy: number, x2: number, y2: number): this; ``` ##### bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x2, y2) <a id="path-context-bezier-curve-to-method"></a> Draw a Cubic Bézier curve from the current position to the end point specified by `x` and `y`, using the control point specified by (`cp1x`, `cp1y`) and (`cp2x`, `cp2y`). Add an instance of [CubicBezierCurve](#cubic-bezier-curve) to the path. - `cp1x`: X-axis coordinate of the first control point. - `cp1y`: Y-axis coordinate of the first control point. - `cp2x`: X-axis coordinate of the second control point. - `cp2y`: Y-axis coordinate of the second control point. - `x2`: X-axis coordinate of the end point. - `y2`: Y-axis coordinate of the end point. ```ts PathContext.bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x2: number, y2: number): this; ``` ##### catmullRomCurveTo(cp1x, cp1y, cp2x, cp2y, x2, y2) <a id="path-context-catmull-rom-curve-to-method"></a> Draw a Catmull-Rom curve from the current position to the end point specified by `x` and `y`, using the control points specified by (`cp1x`, `cp1y`) and (`cp2x`, `cp2y`). Add an instance of [CatmullRomCurve](#catmull-rom-curve) to the path. - `cp1x`: X-axis coordinate of the first control point. - `cp1y`: Y-axis coordinate of the first control point. - `cp2x`: X-axis coordinate of the second control point. - `cp2y`: Y-axis coordinate of the second control point. - `x2`: X-axis coordinate of the end point. - `y2`: Y-axis coordinate of the end point. ```ts PathContext.catmullRomCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x2: number, y2: number): this; ``` ##### splineTo(points) <a id="path-context-spline-to-method"></a> Draw a Spline curve from the current position through the given points. Add an instance of [SplineCurve](#spline-curve) to the path. - `points`: Array of points defining the curve. ```ts PathContext.splineTo(points: Array<[number, number]>): this; ``` ##### ellipse(cx, cy, rx, ry, rotation, startAngle, endAngle, counterclockwise) <a id="path-context-ellipse-method"></a> Draw an Ellispe curve which is centered at (`cx`, `cy`) position. Add an instance of [EllipseCurve](#ellipse-curve) to the path. - `cx`: X-axis coordinate of the center of the ellipse. - `cy`: Y-axis coordinate of the center of the ellipse. - `rx`: X-radius of the ellipse. - `ry`: Y-radius of the ellipse. - `[rotation]`: Rotation angle of the ellipse (in radians), counterclockwise from the positive X-axis. - `[startAngle]`: Start angle of the arc (in radians). - `[endAngle]`: End angle of the arc (in radians). - `[counterclockwise]`: Flag indicating the direction of the arc. ```ts PathContext.ellipse(cx: number, cy: number, rx: number, ry: number, rotation?: number, startAngle?: number, endAngle?: number, counterclockwise?: boolean): this; ``` ##### arc(cx, cy, radius, startAngle, endAngle, counterclockwise) <a id="path-context-arc-method"></a> Draw an Arc curve which is centered at (`cx`, `cy`) position. Add an instance of [ArcCurve](#arc-curve) to the path. - `cx`: X-axis coordinate of the center of the circle. - `cy`: Y-axis coordinate of the center of the circle. - `radius`: Radius of the circle. - `[startAngle]`: Start angle of the arc (in radians). - `[endAngle]`: End angle of the arc (in radians). - `[counterclockwise]`: Flag indicating the direction of the arc. ```ts PathContext.arc(cx: number, cy: number, radius: number, startAngle?: number, endAngle?: number, counterclockwise?: boolean): this; ``` ##### rect(x, y, width, height) <a id="path-context-rect-method"></a> Draw a rectangular path from the start position specified by `x` and `y` to the end position using `width` and `height`. Add an instance of [PolylineCurve](#polyline-curve) to the path. - `x`: X-axis coordinate of the rectangle starting point. - `y`: Y-axis coordinate of the rectangle starting point. - `width`: Rectangle width (Positive values are to the right and negative to the left). - `height`: Rectangle height (Positive values are down, and negative are up). ```ts PathContext.rect(x: number, y: number, width: number, height: number): this; ``` ##### roundRect(x, y, width, height, radius) <a id="path-context-round-rect-method"></a> Draw a rounded rectangular path from the start position specified by `x` and `y` to the end position using `width` and `height`. - `x`: X-axis coordinate of the rectangle starting point. - `y`: Y-axis coordinate of the rectangle starting point. - `width`: Rectangle width (Positive values are to the right and negative to the left). - `height`: Rectangle height (Positive values are down, and negative are up). - `radius`: Radius of the circular arc to be used for the corners of the rectangle. ```ts PathContext.roundRect(x: number, y: number, width: number, height: number, radius: number | number[]): this; ``` ### PathSVG <a id="path-svg"></a> Utility class extending [PathContext](#path-context) for manipulating connected curves and generating SVG path. It works by serializing 2D Canvas API to SVG path data. - [new PathSVG()](#path-svg-constructor) - `static` [.serialize(curve, params)](#path-svg-static-serialize-method): `string` - `static` [.serializeLineCurve(curve)](#path-svg-static-serialize-line-curve-method): `string` - `static` [.serializePolylineCurve(curve)](#path-svg-static-serialize-polyline-curve-method): `string` - `static` [.serializeQuadraticBezierCurve(curve)](#path-svg-static-serialize-quadratic-bezier-curve-method): `string` - `static` [.serializeCubicBezierCurve(curve)](#path-svg-static-serialize-cubic-bezier-curve-method): `string` - `static` [.serializeCatmullRomCurve(curve, params)](#path-svg-static-serialize-catmull-rom-curve-method): `string` - `static` [.serializeSplineCurve(curve, params)](#path-svg-static-serialize-spline-curve-method): `string` - `static` [.serializeEllipseCurve(curve)](#path-svg-static-serialize-ellipse-curve-method): `string` - `static` [.serializeArcCurve(curve)](#path-svg-static-serialize-arc-curve-method): `string` - [.toString(params)](#path-svg-to-string-method): `string` #### Methods ##### serialize(curve) <a id="path-svg-static-serialize-method"></a> Serialize a [Curve](#curve) ```ts static PathSVG.serialize(curve: Curve, params: object): string; ``` ##### serializeLineCurve(curve) <a id="path-svg-static-serialize-line-curve-method"></a> Serialize a [LineCurve](#line-curve) ```ts static PathSVG.serializeLineCurve(curve: LineCurve): string; ``` ##### serializePolylineCurve(curve) <a id="path-svg-static-serialize-polyline-method"></a> Serialize a [PolylineCurve](#polyline-curve). ```ts static PathSVG.serializePolylineCurve(curve: PolylineCurve): string; ``` ##### serializeQuadraticBezierCurve(curve) <a id="path-svg-static-serialize-quadratic-bezier-method"></a> Serialize a [QuadraticBezierCurve](#quadratic-bezier-curve). ```ts static PathSVG.serializeQuadraticBezierCurve(curve: QuadraticBezierCurve): string; ``` ##### serializeCubicBezierCurve(curve) <a id="path-svg-static-serialize-cubic-bezier-method"></a> Serialize a [CubicBezierCurve](#cubic-bezier-curve). ```ts static PathSVG.serializeCubicBezierCurve(curve: CubicBezierCurve): string; ```