@types/fabric
Version:
TypeScript definitions for fabric
1,522 lines (1,422 loc) • 227 kB
TypeScript
// This module does not really exist.
// This is just to get `export as namespace fabric;` to work and to be re-exportable from `index.d.ts`.
export as namespace fabric;
export const isLikelyNode: boolean;
export const isTouchSupported: boolean;
export const version: string;
export const iMatrix: number[];
export let textureSize: number;
export let copiedText: string;
export let copiedTextStyle: any[];
export let charWidthsCache: {
[key: string]: { // example: montserrat
[key: string]: { // example: normal_normal
[key: string]: number; // example: A: 286
};
};
};
/////////////////////////////////////////////////////////////
// fabric Functions
/////////////////////////////////////////////////////////////
export function createCanvasForNode(width: number, height: number): Canvas;
// Parse
// ----------------------------------------------------------
/**
* Creates markup containing SVG referenced elements like patterns, gradients etc.
* @param canvas instance of fabric.Canvas
*/
export function createSVGRefElementsMarkup(canvas: StaticCanvas): string;
/**
* Creates markup containing SVG font faces
* @param objects Array of fabric objects
*/
export function createSVGFontFacesMarkup(objects: Object[]): string;
/**
* Takes string corresponding to an SVG document, and parses it into a set of fabric objects
* @param [reviver] Method for further parsing of SVG elements, called after each fabric object created.
*/
export function loadSVGFromString(
string: string,
callback: (results: Object[], options: any) => void,
reviver?: Function,
): void;
/**
* Takes url corresponding to an SVG document, and parses it into a set of fabric objects.
* Note that SVG is fetched via XMLHttpRequest, so it needs to conform to SOP (Same Origin Policy)
* @param {String} url URL to get a SVG from
* @param {Function} callback Callback is invoked when svg has been loaded
* @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created.
* @param {Object} [options] options for crossOrigin
* @param {String} [options.crossOrigin] crossOrigin settings
*/
export function loadSVGFromURL(
url: string,
callback: (results: Object[], options: any) => void,
reviver?: Function,
options?: { crossOrigin?: string | undefined },
): void;
/**
* Returns CSS rules for a given SVG document
* @param doc SVG document to parse
*/
export function getCSSRules(doc: SVGElement): any;
export function parseElements(elements: any[], callback: Function, options: any, reviver?: Function): void;
/**
* Parses "points" attribute, returning an array of values
* @param points points attribute string
*/
export function parsePointsAttribute(points: string): any[];
/**
* Parses "style" attribute, retuning an object with values
* @param element Element to parse
*/
export function parseStyleAttribute(element: SVGElement): any;
/**
* Transforms an array of svg elements to corresponding fabric.* instances
* @param elements Array of elements to parse
* @param callback Being passed an array of fabric instances (transformed from SVG elements)
* @param [options] Options object
* @param [reviver] Method for further parsing of SVG elements, called after each fabric object created.
*/
export function parseElements(elements: SVGElement[], callback: Function, options?: any, reviver?: Function): void;
/**
* Returns an object of attributes' name/value, given element and an array of attribute names;
* Parses parent "g" nodes recursively upwards.
* @param element Element to parse
* @param attributes Array of attributes to parse
*/
export function parseAttributes(element: HTMLElement, attributes: string[], svgUid?: string): { [key: string]: string };
/**
* Parses an SVG document, returning all of the gradient declarations found in it
* @param doc SVG document to parse
*/
export function getGradientDefs(doc: SVGElement): { [key: string]: any };
/**
* Parses a short font declaration, building adding its properties to a style object
* @param value font declaration
* @param oStyle definition
*/
export function parseFontDeclaration(value: string, oStyle: any): void;
/**
* Parses an SVG document, converts it to an array of corresponding fabric.* instances and passes them to a callback
* @param doc SVG document to parse
* @param callback Callback to call when parsing is finished; It's being passed an array of elements (parsed from a document).
* @param [reviver] Method for further parsing of SVG elements, called after each fabric object created.
*/
export function parseSVGDocument(
doc: SVGElement,
callback: (results: Object[], options: any) => void,
reviver?: Function,
): void;
/**
* Parses "transform" attribute, returning an array of values
* @param attributeValue String containing attribute value
*/
export function parseTransformAttribute(attributeValue: string): number[];
// fabric Log
// ---------------
/**
* Wrapper around `console.log` (when available)
*/
export function log(...values: any[]): void;
/**
* Wrapper around `console.warn` (when available)
*/
export function warn(...values: any[]): void;
///////////////////////////////////////////////////////////////////////////////
// Data Object Interfaces - These interface are not specific part of fabric,
// They are just helpful for for defining function parameters
//////////////////////////////////////////////////////////////////////////////
interface IDataURLOptions {
/**
* The format of the output image. Either "jpeg" or "png"
*/
format?: string | undefined;
/**
* Quality level (0..1). Only used for jpeg
*/
quality?: number | undefined;
/**
* Multiplier to scale by
*/
multiplier?: number | undefined;
/**
* Cropping left offset. Introduced in v1.2.14
*/
left?: number | undefined;
/**
* Cropping top offset. Introduced in v1.2.14
*/
top?: number | undefined;
/**
* Cropping width. Introduced in v1.2.14
*/
width?: number | undefined;
/**
* Cropping height. Introduced in v1.2.14
*/
height?: number | undefined;
enableRetinaScaling?: boolean | undefined;
withoutTransform?: boolean | undefined;
withoutShadow?: boolean | undefined;
}
interface IEvent<E extends Event = Event> {
e: E;
target?: Object | undefined;
subTargets?: Object[] | undefined;
selected?: Object[] | undefined;
deselected?: Object[] | undefined;
action?: string | undefined;
button?: number | undefined;
isClick?: boolean | undefined;
pointer?: Point | undefined;
absolutePointer?: Point | undefined;
transform?: Transform | undefined;
currentTarget?: Object | undefined;
currentSubTargets?: Object[] | undefined;
}
interface IFillOptions {
/**
* options.source Pattern source
*/
source: string | HTMLImageElement;
/**
* Repeat property of a pattern (one of repeat, repeat-x, repeat-y or no-repeat)
*/
repeat?: string | undefined;
/**
* Pattern horizontal offset from object's left/top corner
*/
offsetX?: number | undefined;
/**
* Pattern vertical offset from object's left/top corner
*/
offsetY?: number | undefined;
}
interface IToSVGOptions {
/**
* If true xml tag is not included
*/
suppressPreamble?: boolean | undefined;
/**
* SVG viewbox object
*/
viewBox?: IViewBox | undefined;
/**
* Encoding of SVG output
*/
encoding?: string | undefined;
/**
* desired width of svg with or without units
*/
width?: number | string | undefined;
/**
* desired height of svg with or without units
*/
height?: number | string | undefined;
}
interface IViewBox {
/**
* x-cooridnate of viewbox
*/
x: number;
/**
* y-coordinate of viewbox
*/
y: number;
/**
* Width of viewbox
*/
width: number;
/**
* Height of viewbox
*/
height: number;
}
///////////////////////////////////////////////////////////////////////////////
// Mixins Interfaces
//////////////////////////////////////////////////////////////////////////////
interface ICollection<T> {
_objects: Object[];
/**
* Adds objects to collection, then renders canvas (if `renderOnAddRemove` is not `false`)
* Objects should be instances of (or inherit from) fabric.Object
* @param object Zero or more fabric instances
*/
add(...object: Object[]): T;
/**
* Inserts an object into collection at specified index, then renders canvas (if `renderOnAddRemove` is not `false`)
* An object should be an instance of (or inherit from) fabric.Object
* @param object Object to insert
* @param index Index to insert object at
* @param nonSplicing When `true`, no splicing (shifting) of objects occurs
* @return thisArg
* @chainable
*/
insertAt(object: Object, index: number, nonSplicing: boolean): T;
/**
* Removes objects from a collection, then renders canvas (if `renderOnAddRemove` is not `false`)
* @param object Zero or more fabric instances
* @return thisArg
* @chainable
*/
remove(...object: Object[]): T;
/**
* Executes given function for each object in this group
* @param context Context (aka thisObject)
* @return thisArg
*/
forEachObject(callback: (element: Object, index: number, array: Object[]) => void, context?: any): T;
/**
* Returns an array of children objects of this instance
* Type parameter introduced in 1.3.10
* @param [type] When specified, only objects of this type are returned
*/
getObjects(type?: string): Object[];
/**
* Returns object at specified index
* @return thisArg
*/
item(index: number): T;
/**
* Returns true if collection contains no objects
* @return true if collection is empty
*/
isEmpty(): boolean;
/**
* Returns a size of a collection (i.e: length of an array containing its objects)
* @return Collection size
*/
size(): number;
/**
* Returns true if collection contains an object
* @param object Object to check against
* @return `true` if collection contains an object
*/
contains(object: Object): boolean;
/**
* Returns number representation of a collection complexity
* @return complexity
*/
complexity(): number;
}
type EventName =
| "object:modified"
| "object:moving"
| "object:scaling"
| "object:rotating"
| "object:skewing"
| "object:resizing"
| "object:selected"
| "object:added"
| "object:removed"
| "group:selected"
| "before:transform"
| "before:selection:cleared"
| "selection:cleared"
| "selection:created"
| "selection:updated"
| "mouse:up"
| "mouse:down"
| "mouse:move"
| "mouse:up:before"
| "mouse:down:before"
| "mouse:move:before"
| "mouse:dblclick"
| "mouse:wheel"
| "mouse:over"
| "mouse:out"
| "drop:before"
| "drop"
| "dragover"
| "dragenter"
| "dragleave"
| "before:render"
| "after:render"
| "before:path:created"
| "path:created"
| "canvas:cleared"
| "moving"
| "scaling"
| "rotating"
| "skewing"
| "resizing"
| "mouseup"
| "mousedown"
| "mousemove"
| "mouseup:before"
| "mousedown:before"
| "mousemove:before"
| "mousedblclick"
| "mousewheel"
| "mouseover"
| "mouseout"
| "drop:before"
| "drop"
| "dragover"
| "dragenter"
| "dragleave";
interface IObservable<T> {
/**
* Observes specified event
* @param eventName Event name (eg. 'after:render')
* @param handler Function that receives a notification when an event of the specified type occurs
*/
on(eventName: EventName, handler: (e: IEvent<MouseEvent>) => void): T;
on(eventName: "mouse:wheel", handler: (e: IEvent<WheelEvent>) => void): T;
on(eventName: string, handler: (e: IEvent) => void): T;
/**
* Stops event observing for a particular event handler. Calling this method
* without arguments removes all handlers for all events
* @param eventName Event name (eg. 'after:render') or object with key/value pairs (eg. {'after:render': handler, 'selection:cleared': handler})
* @param handler Function to be deleted from EventListeners
*/
off(eventName?: string | any, handler?: (e: IEvent) => void): T;
/**
* Fires event with an optional options object
* @param {String} eventName Event name to fire
* @param {Object} [options] Options object
* @return {Self} thisArg
* @chainable
*/
fire(eventName: string, options?: any): T;
}
interface Callbacks {
/** Invoked on completion */
onComplete?: Function | undefined;
/** Invoked on every step of animation */
onChange?: Function | undefined;
}
// animation mixin
// ----------------------------------------------------
interface ICanvasAnimation<T> {
FX_DURATION: number;
/**
* Centers object horizontally with animation.
* @param object Object to center
*/
fxCenterObjectH(object: Object, callbacks?: Callbacks): T;
/**
* Centers object vertically with animation.
* @param object Object to center
*/
fxCenterObjectV(object: Object, callbacks?: Callbacks): T;
/**
* Same as `fabric.Canvas#remove` but animated
* @param object Object to remove
* @chainable
*/
fxRemove(object: Object): T;
/**
* Same as {@link fabric.Canvas.prototype.straightenObject}, but animated
* @param {fabric.Object} object Object to straighten
* @return {fabric.Canvas} thisArg
* @chainable
*/
fxStraightenObject(object: Object): T;
}
interface IObjectAnimation<T> {
/**
* Animates object's properties
* object.animate('left', ..., {duration: ...});
* @param property Property to animate
* @param value Value to animate property
* @param options The animation options
*/
animate(property: string, value: number | string, options?: IAnimationOptions): Object;
/**
* Animates object's properties
* object.animate({ left: ..., top: ... }, { duration: ... });
* @param properties Properties to animate with values to animate to
* @param options The animation options
*/
animate(properties: { [key: string]: number | string }, options?: IAnimationOptions): Object;
}
interface IAnimationOptions {
/**
* Allows to specify starting value of animatable property (if we don't want current value to be used).
*/
from?: string | number | undefined;
/**
* Defaults to 500 (ms). Can be used to change duration of an animation.
*/
duration?: number | undefined;
/**
* Callback; invoked on every value change
*/
onChange?: Function | undefined;
/**
* Callback; invoked when value change is completed
*/
onComplete?: Function | undefined;
/**
* Easing function. Default: fabric.util.ease.easeInSine
*/
easing?: Function | undefined;
/**
* Value to modify the property by, default: end - start
*/
by?: number | undefined;
}
///////////////////////////////////////////////////////////////////////////////
// General Fabric Interfaces
//////////////////////////////////////////////////////////////////////////////
export class Color {
/**
* Color class
* The purpose of Color is to abstract and encapsulate common color operations;
* @param color optional in hex or rgb(a) format
*/
constructor(color?: string);
/**
* Returns source of this color (where source is an array representation; ex: [200, 200, 100, 1])
*/
getSource(): number[];
/**
* Sets source of this color (where source is an array representation; ex: [200, 200, 100, 1])
*/
setSource(source: number[]): void;
/**
* Returns color represenation in RGB format ex: rgb(0-255,0-255,0-255)
*/
toRgb(): string;
/**
* Returns color represenation in RGBA format ex: rgba(0-255,0-255,0-255,0-1)
*/
toRgba(): string;
/**
* Returns color represenation in HSL format ex: hsl(0-360,0%-100%,0%-100%)
*/
toHsl(): string;
/**
* Returns color represenation in HSLA format ex: hsla(0-360,0%-100%,0%-100%,0-1)
*/
toHsla(): string;
/**
* Returns color represenation in HEX format ex: FF5555
*/
toHex(): string;
/**
* Returns color representation in HEXA format
* @return {String} ex: FF5555CC
*/
toHexa(): string;
/**
* Gets value of alpha channel for this color
*/
getAlpha(): number;
/**
* Sets value of alpha channel for this color
* @param alpha Alpha value 0-1
*/
setAlpha(alpha: number): void;
/**
* Transforms color to its grayscale representation
*/
toGrayscale(): Color;
/**
* Transforms color to its black and white representation
*/
toBlackWhite(threshold: number): Color;
/**
* Overlays color with another color
*/
overlayWith(otherColor: string | Color): Color;
/**
* Returns new color object, when given a color in RGB format
* @param color Color value ex: rgb(0-255,0-255,0-255)
*/
static fromRgb(color: string): Color;
/**
* Returns new color object, when given a color in RGBA format
* @param color Color value ex: rgb(0-255,0-255,0-255)
*/
static fromRgba(color: string): Color;
/**
* Returns array represenatation (ex: [100, 100, 200, 1]) of a color that's in RGB or RGBA format
* @param color Color value ex: rgb(0-255,0-255,0-255), rgb(0%-100%,0%-100%,0%-100%)
*/
static sourceFromRgb(color: string): number[];
/**
* Returns new color object, when given a color in HSL format
* @param color Color value ex: hsl(0-260,0%-100%,0%-100%)
*/
static fromHsl(color: string): Color;
/**
* Returns new color object, when given a color in HSLA format
* @param color Color value ex: hsl(0-260,0%-100%,0%-100%)
*/
static fromHsla(color: string): Color;
/**
* Returns array represenatation (ex: [100, 100, 200, 1]) of a color that's in HSL or HSLA format.
* @param color Color value ex: hsl(0-360,0%-100%,0%-100%) or hsla(0-360,0%-100%,0%-100%, 0-1)
*/
static sourceFromHsl(color: string): number[];
/**
* Returns new color object, when given a color in HEX format
* @param color Color value ex: FF5555
*/
static fromHex(color: string): Color;
/**
* Returns array represenatation (ex: [100, 100, 200, 1]) of a color that's in HEX format
* @param color ex: FF5555
*/
static sourceFromHex(color: string): number[];
/**
* Returns new color object, when given color in array representation (ex: [200, 100, 100, 0.5])
*/
static fromSource(source: number[]): Color;
/**
* Regex matching color in HEX format (ex: #FF5544CC, #FF5555, 010155, aff)
* @static
* @field
*/
static reHex: RegExp;
/**
* Regex matching color in HSL or HSLA formats (ex: hsl(200, 80%, 10%), hsla(300, 50%, 80%, 0.5), hsla( 300 , 50% , 80% , 0.5 ))
* @static
* @field
*/
static reHSLa: RegExp;
/**
* Regex matching color in RGB or RGBA formats (ex: rgb(0, 0, 0), rgba(255, 100, 10, 0.5), rgba( 255 , 100 , 10 , 0.5 ), rgb(1,1,1), rgba(100%, 60%, 10%, 0.5))
* @static
* @field
*/
static reRGBa: RegExp;
}
interface IGradientOptionsCoords {
x1?: number | undefined;
y1?: number | undefined;
x2?: number | undefined;
y2?: number | undefined;
r1?: number | undefined;
r2?: number | undefined;
}
type IGradientOptionsColorStops = Array<{
offset: number;
color: string;
}>;
interface IGradientOptions {
/**
* Horizontal offset for aligning gradients coming from SVG when outside pathgroups
*/
offsetX?: number | undefined;
/**
* Vertical offset for aligning gradients coming from SVG when outside pathgroups
*/
offsetY?: number | undefined;
type?: string | undefined;
coords?: IGradientOptionsCoords | undefined;
/**
* Color stops object eg. {0:string; 1:string;
*/
colorStops?: IGradientOptionsColorStops | undefined;
gradientTransform?: any;
}
interface OGradientOptions {
type?: string | undefined;
x1?: number | undefined;
y1?: number | undefined;
x2?: number | undefined;
y2?: number | undefined;
r1?: number | undefined;
r2?: number | undefined;
colorStops?: {
[key: string]: string;
} | undefined;
gradientTransform?: any;
}
export interface Gradient extends IGradientOptions {}
export class Gradient {
/**
* Constructor
* @param {Object} options Options object with type, coords, gradientUnits and colorStops
* @param {Object} [options.type] gradient type linear or radial
* @param {Object} [options.gradientUnits] gradient units
* @param {Object} [options.offsetX] SVG import compatibility
* @param {Object} [options.offsetY] SVG import compatibility
* @param {Object[]} options.colorStops contains the colorstops.
* @param {Object} options.coords contains the coords of the gradient
* @param {Number} [options.coords.x1] X coordiante of the first point for linear or of the focal point for radial
* @param {Number} [options.coords.y1] Y coordiante of the first point for linear or of the focal point for radial
* @param {Number} [options.coords.x2] X coordiante of the second point for linear or of the center point for radial
* @param {Number} [options.coords.y2] Y coordiante of the second point for linear or of the center point for radial
* @param {Number} [options.coords.r1] only for radial gradient, radius of the inner circle
* @param {Number} [options.coords.r2] only for radial gradient, radius of the external circle
* @return {fabric.Gradient} thisArg
*/
constructor(options: {
type?: string | undefined;
gradientUnits?: any;
offsetX?: any;
offsetY?: any;
colorStops?: IGradientOptionsColorStops | undefined;
coords?: IGradientOptionsCoords | undefined;
});
/**
* Adds another colorStop
* @param colorStop Object with offset and color
*/
addColorStop(colorStop: any): Gradient;
/**
* Returns object representation of a gradient
*/
toObject(propertiesToInclude?: any): any;
/**
* Returns SVG representation of an gradient
* @param {Object} object Object to create a gradient for
* @return {String} SVG representation of an gradient (linear/radial)
*/
toSVG(object: any): string;
/**
* Returns an instance of CanvasGradient
* @param ctx Context to render on
*/
toLive(ctx: CanvasRenderingContext2D): CanvasGradient;
/**
* Returns {@link fabric.Gradient} instance from an SVG element
* @static
* @param {SVGGradientElement} el SVG gradient element
* @param {fabric.Object} instance
* @return {fabric.Gradient} Gradient instance
* @see http://www.w3.org/TR/SVG/pservers.html#LinearGradientElement
* @see http://www.w3.org/TR/SVG/pservers.html#RadialGradientElement
*/
static fromElement(el: SVGGradientElement, instance: Object): Gradient;
}
export class Intersection {
status?: string | undefined;
points?: Point[] | undefined;
constructor(status?: string);
/**
* Appends a point to intersection
*/
appendPoint(point: Point): Intersection;
/**
* Appends points to intersection
*/
appendPoints(points: Point[]): Intersection;
/**
* Checks if one line intersects another
*/
static intersectLineLine(a1: Point, a2: Point, b1: Point, b2: Point): Intersection;
/**
* Checks if line intersects polygon
*/
static intersectLinePolygon(a1: Point, a2: Point, points: Point[]): Intersection;
/**
* Checks if polygon intersects another polygon
*/
static intersectPolygonPolygon(points1: Point[], points2: Point[]): Intersection;
/**
* Checks if polygon intersects rectangle
*/
static intersectPolygonRectangle(points: Point[], r1: Point, r2: Point): Intersection;
}
interface IPatternOptions {
/**
* Repeat property of a pattern (one of repeat, repeat-x, repeat-y or no-repeat)
*/
repeat?: string | undefined;
/**
* Pattern horizontal offset from object's left/top corner
*/
offsetX?: number | undefined;
/**
* Pattern vertical offset from object's left/top corner
*/
offsetY?: number | undefined;
/**
* crossOrigin value (one of "", "anonymous", "use-credentials")
* @see https://developer.mozilla.org/en-US/docs/HTML/CORS_settings_attributes
*/
crossOrigin?: "" | "anonymous" | "use-credentials" | undefined;
/**
* Transform matrix to change the pattern, imported from svgs
*/
patternTransform?: number[] | undefined;
/**
* The source for the pattern
*/
source: string | HTMLImageElement;
}
export interface Pattern extends IPatternOptions {}
export class Pattern {
/**
* Unique identifier
*/
id: number;
constructor(options?: IPatternOptions);
/**
* Returns object representation of a pattern
* @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
* @return {Object} Object representation of a pattern instance
*/
toObject(propertiesToInclude: any): any;
/**
* Returns SVG representation of a pattern
* @param {fabric.Object} object
* @return {String} SVG representation of a pattern
*/
toSVG(object: Object): string;
setOptions(options: IPatternOptions): void;
/**
* Returns an instance of CanvasPattern
* @param {CanvasRenderingContext2D} ctx Context to create pattern
* @return {CanvasPattern}
*/
toLive(ctx: CanvasRenderingContext2D): CanvasPattern;
}
interface IPoint {
x: number;
y: number;
}
export class Point implements IPoint {
x: number;
y: number;
type: string;
constructor(x: number, y: number);
/**
* Adds another point to this one and returns another one
* @param {fabric.Point} that
* @return {fabric.Point} new Point instance with added values
*/
add(that: IPoint): Point;
/**
* Adds another point to this one
* @param {fabric.Point} that
* @return {fabric.Point} thisArg
* @chainable
*/
addEquals(that: IPoint): Point;
/**
* Adds value to this point and returns a new one
* @param {Number} scalar
* @return {fabric.Point} new Point with added value
*/
scalarAdd(scalar: number): Point;
/**
* Adds value to this point
* @param {Number} scalar
* @return {fabric.Point} thisArg
* @chainable
*/
scalarAddEquals(scalar: number): Point;
/**
* Subtracts another point from this point and returns a new one
* @param {fabric.Point} that
* @return {fabric.Point} new Point object with subtracted values
*/
subtract(that: IPoint): Point;
/**
* Subtracts another point from this point
* @param {fabric.Point} that
* @return {fabric.Point} thisArg
* @chainable
*/
subtractEquals(that: IPoint): Point;
/**
* Subtracts value from this point and returns a new one
* @param {Number} scalar
* @return {fabric.Point}
*/
scalarSubtract(scalar: number): Point;
/**
* Subtracts value from this point
* @param {Number} scalar
* @return {fabric.Point} thisArg
* @chainable
*/
scalarSubtractEquals(scalar: number): Point;
/**
* Multiplies this point by a value and returns a new one
* @param {Number} scalar
* @return {fabric.Point}
*/
multiply(scalar: number): Point;
/**
* Multiplies this point by a value
* @param {Number} scalar
* @return {fabric.Point} thisArg
* @chainable
*/
multiplyEquals(scalar: number): Point;
/**
* Divides this point by a value and returns a new one
* @param {Number} scalar
* @return {fabric.Point}
*/
divide(scalar: number): Point;
/**
* Divides this point by a value
* @param {Number} scalar
* @return {fabric.Point} thisArg
* @chainable
*/
divideEquals(scalar: number): Point;
/**
* Returns true if this point is equal to another one
* @param {fabric.Point} that
* @return {Boolean}
*/
eq(that: IPoint): Point;
/**
* Returns true if this point is less than another one
* @param {fabric.Point} that
* @return {Boolean}
*/
lt(that: IPoint): Point;
/**
* Returns true if this point is less than or equal to another one
* @param {fabric.Point} that
* @return {Boolean}
*/
lte(that: IPoint): Point;
/**
* Returns true if this point is greater another one
* @param {fabric.Point} that
* @return {Boolean}
*/
gt(that: IPoint): Point;
/**
* Returns true if this point is greater than or equal to another one
* @param {fabric.Point} that
* @return {Boolean}
*/
gte(that: IPoint): Point;
/**
* Returns new point which is the result of linear interpolation with this one and another one
* @param {fabric.Point} that
* @param {Number} t , position of interpolation, between 0 and 1 default 0.5
* @return {fabric.Point}
*/
lerp(that: IPoint, t: number): Point;
/**
* Returns distance from this point and another one
* @param {fabric.Point} that
* @return {Number}
*/
distanceFrom(that: IPoint): number;
/**
* Returns the point between this point and another one
* @param {fabric.Point} that
* @return {fabric.Point}
*/
midPointFrom(that: IPoint): Point;
/**
* Returns a new point which is the min of this and another one
* @param {fabric.Point} that
* @return {fabric.Point}
*/
min(that: IPoint): Point;
/**
* Returns a new point which is the max of this and another one
* @param {fabric.Point} that
* @return {fabric.Point}
*/
max(that: IPoint): Point;
/**
* Returns string representation of this point
* @return {String}
*/
toString(): string;
/**
* Sets x/y of this point
* @param {Number} x
* @param {Number} y
* @chainable
*/
setXY(x: number, y: number): Point;
/**
* Sets x of this point
* @param {Number} x
* @chainable
*/
setX(x: number): Point;
/**
* Sets y of this point
* @param {Number} y
* @chainable
*/
setY(y: number): Point;
/**
* Sets x/y of this point from another point
* @param {fabric.Point} that
* @chainable
*/
setFromPoint(that: IPoint): Point;
/**
* Swaps x/y of this point and another point
* @param {fabric.Point} that
*/
swap(that: IPoint): Point;
/**
* return a cloned instance of the point
* @return {fabric.Point}
*/
clone(): Point;
}
interface IShadowOptions {
/**
* Shadow color
*/
color?: string | undefined;
/**
* Shadow blur
*/
blur?: number | undefined;
/**
* Shadow horizontal offset
*/
offsetX?: number | undefined;
/**
* Shadow vertical offset
*/
offsetY?: number | undefined;
/**
* Whether the shadow should affect stroke operations
*/
affectStroke?: boolean | undefined;
/**
* Indicates whether toObject should include default values
*/
includeDefaultValues?: boolean | undefined;
/**
* When `false`, the shadow will scale with the object.
* When `true`, the shadow's offsetX, offsetY, and blur will not be affected by the object's scale.
* default to false
* @default
*/
nonScaling?: boolean | undefined;
}
export interface Shadow extends IShadowOptions {}
export class Shadow {
constructor(options?: IShadowOptions | string);
initialize(options?: IShadowOptions | string): Shadow;
/**
* Returns a string representation of an instance
* @see http://www.w3.org/TR/css-text-decor-3/#text-shadow
* @return {String} Returns CSS3 text-shadow declaration
*/
toString(): string;
/**
* Returns SVG representation of a shadow
* @param {fabric.Object} object
* @return {String} SVG representation of a shadow
*/
toSVG(object: Object): string;
/**
* Returns object representation of a shadow
* @return {Object} Object representation of a shadow instance
*/
toObject(): any;
/**
* Regex matching shadow offsetX, offsetY and blur (ex: "2px 2px 10px rgba(0,0,0,0.2)", "rgb(0,255,0) 2px 2px")
* @static
* @field
*/
static reOffsetsAndBlur: RegExp;
}
///////////////////////////////////////////////////////////////////////////////
// Canvas Interfaces
//////////////////////////////////////////////////////////////////////////////
interface ICanvasDimensions {
/**
* Width of canvas element
*/
width: number | string;
/**
* Height of canvas element
*/
height: number | string;
}
interface ICanvasDimensionsOptions {
/**
* Set the given dimensions only as canvas backstore dimensions
*/
backstoreOnly?: boolean | undefined;
/**
* Set the given dimensions only as css dimensions
*/
cssOnly?: boolean | undefined;
}
interface IStaticCanvasOptions {
/**
* Background color of canvas instance.
* Should be set via {@link fabric.StaticCanvas#setBackgroundColor}.
*/
backgroundColor?: string | Pattern | undefined;
/**
* Background image of canvas instance.
* Should be set via {@link fabric.StaticCanvas#setBackgroundImage}.
* <b>Backwards incompatibility note:</b> The "backgroundImageOpacity"
* and "backgroundImageStretch" properties are deprecated since 1.3.9.
* Use {@link fabric.Image#opacity}, {@link fabric.Image#width} and {@link fabric.Image#height}.
* since 2.4.0 image caching is active, please when putting an image as background, add to the
* canvas property a reference to the canvas it is on. Otherwise the image cannot detect the zoom
* vale. As an alternative you can disable image objectCaching
*/
backgroundImage?: Image | string | undefined;
/**
* Overlay color of canvas instance.
* Should be set via {@link fabric.StaticCanvas#setOverlayColor}
* @since 1.3.9
*/
overlayColor?: string | Pattern | undefined;
/**
* Overlay image of canvas instance.
* Should be set via {@link fabric.StaticCanvas#setOverlayImage}.
* <b>Backwards incompatibility note:</b> The "overlayImageLeft"
* and "overlayImageTop" properties are deprecated since 1.3.9.
* Use {@link fabric.Image#left} and {@link fabric.Image#top}.
* since 2.4.0 image caching is active, please when putting an image as overlay, add to the
* canvas property a reference to the canvas it is on. Otherwise the image cannot detect the zoom
* vale. As an alternative you can disable image objectCaching
*/
overlayImage?: Image | undefined;
/**
* Indicates whether toObject/toDatalessObject should include default values
* if set to false, takes precedence over the object value.
*/
includeDefaultValues?: boolean | undefined;
/**
* Indicates whether objects' state should be saved
*/
stateful?: boolean | undefined;
/**
* Indicates whether {@link fabric.Collection.add}, {@link fabric.Collection.insertAt} and {@link fabric.Collection.remove},
* {@link fabric.StaticCanvas.moveTo}, {@link fabric.StaticCanvas.clear} and many more, should also re-render canvas.
* Disabling this option will not give a performance boost when adding/removing a lot of objects to/from canvas at once
* since the renders are quequed and executed one per frame.
* Disabling is suggested anyway and managing the renders of the app manually is not a big effort ( canvas.requestRenderAll() )
* Left default to true to do not break documentation and old app, fiddles.
*/
renderOnAddRemove?: boolean | undefined;
/**
* Indicates whether object controls (borders/controls) are rendered above overlay image
*/
controlsAboveOverlay?: boolean | undefined;
/**
* Indicates whether the browser can be scrolled when using a touchscreen and dragging on the canvas
*/
allowTouchScrolling?: boolean | undefined;
/**
* Indicates whether this canvas will use image smoothing, this is on by default in browsers
*/
imageSmoothingEnabled?: boolean | undefined;
/**
* The transformation (in the format of Canvas transform) which focuses the viewport
*/
viewportTransform?: number[] | undefined;
/**
* if set to false background image is not affected by viewport transform
* @since 1.6.3
*/
backgroundVpt?: boolean | undefined;
/**
* if set to false overlay image is not affected by viewport transform
* @since 1.6.3
*/
overlayVpt?: boolean | undefined;
/**
* When true, canvas is scaled by devicePixelRatio for better rendering on retina screens
*/
enableRetinaScaling?: boolean | undefined;
/**
* Describe canvas element extension over design
* properties are tl,tr,bl,br.
* if canvas is not zoomed/panned those points are the four corner of canvas
* if canvas is viewportTransformed you those points indicate the extension
* of canvas element in plain untrasformed coordinates
* The coordinates get updated with @method calcViewportBoundaries.
*/
vptCoords?: {
tl: { x: number; y: number };
tr: { x: number; y: number };
bl: { x: number; y: number };
br: { x: number; y: number };
} | undefined;
/**
* Based on vptCoords and object.aCoords, skip rendering of objects that
* are not included in current viewport.
* May greatly help in applications with crowded canvas and use of zoom/pan
* If One of the corner of the bounding box of the object is on the canvas
* the objects get rendered.
*/
skipOffscreen?: boolean | undefined;
/**
* a fabricObject that, without stroke define a clipping area with their shape. filled in black
* the clipPath object gets used when the canvas has rendered, and the context is placed in the
* top left corner of the canvas.
* clipPath will clip away controls, if you do not want this to happen use controlsAboveOverlay = true
*/
clipPath?: Object | undefined;
/**
* When true, getSvgTransform() will apply the StaticCanvas.viewportTransform to the SVG transformation. When true,
* a zoomed canvas will then produce zoomed SVG output.
*/
svgViewportTransformation?: boolean | undefined;
/**
* When the option is enabled, PointerEvent is used instead of MouseEvent.
*/
enablePointerEvents?: boolean | undefined;
}
export interface StaticCanvas
extends IObservable<StaticCanvas>, IStaticCanvasOptions, ICollection<StaticCanvas>, ICanvasAnimation<StaticCanvas>
{
toJSON(propertiesToInclude?: string[]): { version: string; objects: Object[] };
toDatalessJSON(propertiesToInclude?: string[]): { version: string; objects: Object[] };
toObject(propertiesToInclude?: string[]): { version: string; objects: Object[] };
toDatalessObject(propertiesToInclude?: string[]): { version: string; objects: Object[] };
}
export class StaticCanvas {
/**
* Constructor
* @param {HTMLElement | String} el <canvas> element to initialize instance on
* @param {Object} [options] Options object
* @return {Object} thisArg
*/
constructor(element: HTMLCanvasElement | string | null, options?: ICanvasOptions);
_activeObject?: Object | Group | undefined;
freeDrawingBrush: BaseBrush;
/**
* Calculates canvas element offset relative to the document
* This method is also attached as "resize" event handler of window
* @return {fabric.Canvas} instance
* @chainable
*/
calcOffset(): Canvas;
/**
* Sets {@link fabric.StaticCanvas#overlayImage|overlay image} for this canvas
* @param {(fabric.Image|String)} image fabric.Image instance or URL of an image to set overlay to
* @param {Function} callback callback to invoke when image is loaded and set as an overlay
* @param {Object} [options] Optional options to set for the {@link fabric.Image|overlay image}.
* @return {fabric.Canvas} thisArg
* @chainable
*/
setOverlayImage(image: Image | string, callback: Function, options?: IImageOptions): Canvas;
/**
* Sets {@link fabric.StaticCanvas#backgroundImage|background image} for this canvas
* @param {(fabric.Image|String)} image fabric.Image instance or URL of an image to set background to
* @param {Function} callback Callback to invoke when image is loaded and set as background
* @param {Object} [options] Optional options to set for the {@link fabric.Image|background image}.
* @return {fabric.Canvas} thisArg
* @chainable
*/
setBackgroundImage(image: Image | string, callback: Function, options?: IImageOptions): Canvas;
/**
* Sets {@link fabric.StaticCanvas#overlayColor|foreground color} for this canvas
* @param {(String|fabric.Pattern)} overlayColor Color or pattern to set foreground color to
* @param {Function} callback Callback to invoke when foreground color is set
* @return {fabric.Canvas} thisArg
* @chainable
*/
setOverlayColor(overlayColor: string | Pattern, callback: Function): Canvas;
/**
* Sets {@link fabric.StaticCanvas#backgroundColor|background color} for this canvas
* @param {(String|fabric.Pattern)} backgroundColor Color or pattern to set background color to
* @param {Function} callback Callback to invoke when background color is set
* @return {fabric.Canvas} thisArg
* @chainable
*/
setBackgroundColor(backgroundColor: string | Pattern | Gradient, callback: Function): Canvas;
/**
* Returns canvas width (in px)
* @return {Number}
*/
getWidth(): number;
/**
* Returns canvas height (in px)
* @return {Number}
*/
getHeight(): number;
/**
* Sets width of this canvas instance
* @param {Number|String} value Value to set width to
* @param {Object} [options] Options object
* @return {fabric.Canvas} instance
* @chainable true
*/
setWidth(value: number | string, options?: ICanvasDimensionsOptions): Canvas;
/**
* Sets height of this canvas instance
* @param value Value to set height to
* @param [options] Options object
* @return {fabric.Canvas} instance
* @chainable true
*/
setHeight(value: number | string, options?: ICanvasDimensionsOptions): Canvas;
/**
* Sets dimensions (width, height) of this canvas instance. when options.cssOnly flag active you should also supply the unit of measure (px/%/em)
* @param dimensions Object with width/height properties
* @param [options] Options object
* @return {fabric.Canvas} thisArg
* @chainable
*/
setDimensions(dimensions: ICanvasDimensions, options?: ICanvasDimensionsOptions): Canvas;
/**
* Returns canvas zoom level
*/
getZoom(): number;
/**
* Sets viewport transform of this canvas instance
* @param {Array} vpt the transform in the form of context.transform
* @return {fabric.Canvas} instance
* @chainable
*/
setViewportTransform(vpt: number[]): Canvas;
/**
* Sets zoom level of this canvas instance, zoom centered around point
* @param {fabric.Point} point to zoom with respect to
* @param {Number} value to set zoom to, less than 1 zooms out
* @return {fabric.Canvas} instance
* @chainable true
*/
zoomToPoint(point: IPoint, value: number): Canvas;
/**
* Sets zoom level of this canvas instance
* @param {Number} value to set zoom to, less than 1 zooms out
* @return {fabric.Canvas} instance
* @chainable
*/
setZoom(value: number): Canvas;
/**
* Pan viewport so as to place point at top left corner of canvas
* @param {fabric.Point} point to move to
* @return {fabric.Canvas} instance
* @chainable
*/
absolutePan(point: IPoint): Canvas;
/**
* Pans viewpoint relatively
* @param {fabric.Point} point (position vector) to move by
* @return {fabric.Canvas} instance
* @chainable
*/
relativePan(point: IPoint): Canvas;
/**
* Returns <canvas> element corresponding to this instance
* @return {HTMLCanvasElement}
*/
getElement(): HTMLCanvasElement;
/**
* Clears specified context of canvas element
* @param ctx Context to clear
* @chainable
*/
clearContext(ctx: CanvasRenderingContext2D): Canvas;
/**
* Returns context of canvas where objects are drawn
* @return {CanvasRenderingContext2D}
*/
getContext(): CanvasRenderingContext2D;
/**
* Clears all contexts (background, main, top) of an instance
* @return {fabric.Canvas} thisArg
* @chainable
*/
clear(): Canvas;
/**
* Renders the canvas
* @return {fabric.Canvas} instance
* @chainable
*/
renderAll(): Canvas;
/**
* Function created to be instance bound at initialization
* used in requestAnimationFrame rendering
* Let the fabricJS call it. If you call it manually you could have more
* animationFrame stacking on to of each other
* for an imperative rendering, use canvas.renderAll
* @return {fabric.Canvas} instance
* @chainable
*/
renderAndReset(): Canvas;
/**
* Append a renderAll request to next animation frame.
* unless one is already in progress, in that case nothing is done
* a boolean flag will avoid appending more.
* @return {fabric.Canvas} instance
* @chainable
*/
requestRenderAll(): Canvas;
/**
* Calculate the position of the 4 corner of canvas with current viewportTransform.
* helps to determinate when an object is in the current rendering viewport using
* object absolute coordinates ( aCoords )
* @return {Object} points.tl
* @chainable
*/
calcViewportBoundaries(): { tl: Point; br: Point; tr: Point; bl: Point };
/**
* Renders background, objects, overlay and controls.
* @param {CanvasRenderingContext2D} ctx
* @param {Array} objects to render
* @return {fabric.Canvas} instance
* @chainable
*/
renderCanvas(ctx: CanvasRenderingContext2D, objects: Object[]): Canvas;
/**
* Paint the cached clipPath on the lowerCanvasEl
* @param {CanvasRenderingContext2D} ctx Context to render on
*/
drawClipPathOnCanvas(ctx: CanvasRenderingContext2D): void;
/**
* Returns coordinates of a center of canvas.
* Returned value is an object with top and left properties
* @return {Object} object with "top" and "left" number values
*/
getCenter(): { top: number; left: number };
/**
* Centers object horizontally in the canvas
* @param {fabric.Object} object Object to center horizontally
* @return {fabric.Canvas} thisArg
*/
centerObjectH(object: Object): Canvas;
/**
* Centers object vertically in the canvas
* @param {fabric.Object} object Object to center vertically
* @return {fabric.Canvas} thisArg
* @chainable
*/
centerObjectV(object: Object): Canvas;
/**
* Centers object vertically and horizontally in the canvas
* @param {fabric.Object} object Object to center vertically and horizontally
* @return {fabric.Canvas} thisArg
* @chainable
*/
centerObject(object: Object): Canvas;
/**
* Centers object vertically and horizontally in the viewport
* @param {fabric.Object} object Object to center vertically and horizontally
* @return {fabric.Canvas} thisArg
* @chainable
*/
viewportCenterObject(object: Object): Canvas;
/**
* Centers object horizontally in the viewport, object.top is unchanged
* @param {fabric.Object} object Object to center vertically and horizontally
* @return {fabric.Canvas} thisArg
* @chainable
*/
viewportCenterObjectH(object: Object): Canvas;
/**
* Centers object Vertically in the viewport, object.top is unchanged
* @param {fabric.Object} object Object to center vertically and horizontally
* @return {fabric.Canvas} thisArg
* @chainable
*/
viewportCenterObjectV(object: Object): Canvas;
/**
* Calculate the point in canvas that correspond to the center of actual viewport.
* @return {fabric.Point} vpCenter, viewport center
*/
getVpCenter(): Point;
/**
* Returs dataless JSON representation of canvas
* @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
* @return {String} json string
*/
toDatalessJSON(propertiesToInclude?: string[]): { version: string; objects: Obje