UNPKG

sunzi-fabric

Version:

made by fabric@3.2.0

1,622 lines (1,503 loc) 184 kB
// 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 let textureSize: number; ///////////////////////////////////////////////////////////// // 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 [reviver] Method for further parsing of SVG elements, called after each fabric object created. */ export function loadSVGFromURL(url: string, callback: (results: Object[], options: any) => void, reviver?: Function): 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; /** * Quality level (0..1). Only used for jpeg */ quality?: number; /** * Multiplier to scale by */ multiplier?: number; /** * Cropping left offset. Introduced in v1.2.14 */ left?: number; /** * Cropping top offset. Introduced in v1.2.14 */ top?: number; /** * Cropping width. Introduced in v1.2.14 */ width?: number; /** * Cropping height. Introduced in v1.2.14 */ height?: number; enableRetinaScaling?: boolean; withoutTransform?: boolean; withoutShadow?: boolean; } interface IEvent { e: Event; target?: Object; subTargets?: Object[], button?: number; isClick?: boolean; pointer?: Point; absolutePointer?: Point; transform?: { corner: string, original: Object, originX: string, originY: string, width: number }; } 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; /** * Pattern horizontal offset from object's left/top corner */ offsetX?: number; /** * Pattern vertical offset from object's left/top corner */ offsetY?: number; } interface IToSVGOptions { /** * If true xml tag is not included */ suppressPreamble?: boolean; /** * SVG viewbox object */ viewBox?: IViewBox; /** * Encoding of SVG output */ encoding?: string; /** * desired width of svg with or without units */ width?: number; /** * desired height of svg with or without units */ height?: number; } 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> { /** * 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; } 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: string, handler: (e: IEvent) => void): T; /** * Observes specified event * @param eventName Object with key/value pairs (eg. {'after:render': handler, 'selection:cleared': handler}) */ on(events: { [eventName: string]: (e: IEvent) => void }): T; /** * Fires event with an optional options object * @param eventName Event name to fire * @param [options] Options object */ trigger(eventName: string, options?: any): 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; } interface Callbacks { /** Invoked on completion */ onComplete?: Function; /** Invoked on every step of animation */ onChange?: Function; } // 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 * @param value Options object */ animate(properties: any, 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; /** * Defaults to 500 (ms). Can be used to change duration of an animation. */ duration?: number; /** * Callback; invoked on every value change */ onChange?: Function; /** * Callback; invoked when value change is completed */ onComplete?: Function; /** * Easing function. Default: fabric.util.ease.easeInSine */ easing?: Function; /** * Value to modify the property by, default: end - start */ by?: number; } /////////////////////////////////////////////////////////////////////////////// // 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; } interface IGradientOptions { /** * Horizontal offset for aligning gradients coming from SVG when outside pathgroups * @type Number */ offsetX?: number; /** * Vertical offset for aligning gradients coming from SVG when outside pathgroups * @type Number */ offsetY?: number; type?: string; coords?: {x1?: number, y1?: number, x2?: number, y2?: number, r1?: number, r2?: number}; /** * Color stops object eg. {0:string; 1:string; */ colorStops?: any; gradientTransform?: any; } export interface Gradient extends IGradientOptions { } export class Gradient { /** * 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 * @memberOf fabric.Gradient * @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; /** * Returns {@link fabric.Gradient} instance from its object representation * @static * @memberOf fabric.Gradient * @param {Object} obj * @param {Object} [options] Options object */ static forObject(obj: any, options?: IGradientOptions): Gradient; } export class Intersection { 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: number, r2: number): Intersection; } interface IPatternOptions { /** * Repeat property of a pattern (one of repeat, repeat-x, repeat-y or no-repeat) */ repeat?: string; /** * Pattern horizontal offset from object's left/top corner */ offsetX?: number; /** * Pattern vertical offset from object's left/top corner */ offsetY?: number; /** * crossOrigin value (one of "", "anonymous", "use-credentials") * @see https://developer.mozilla.org/en-US/docs/HTML/CORS_settings_attributes * @type String */ crossOrigin?: '' | 'anonymous' | 'use-credentials'; /** * Transform matrix to change the pattern, imported from svgs */ patternTransform?: number[]; /** * 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; } export class Point { 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: Point): Point; /** * Adds another point to this one * @param {fabric.Point} that * @return {fabric.Point} thisArg * @chainable */ addEquals(that: Point): 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: Point): Point; /** * Subtracts another point from this point * @param {fabric.Point} that * @return {fabric.Point} thisArg * @chainable */ subtractEquals(that: Point): 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: Point): Point; /** * Returns true if this point is less than another one * @param {fabric.Point} that * @return {Boolean} */ lt(that: Point): Point; /** * Returns true if this point is less than or equal to another one * @param {fabric.Point} that * @return {Boolean} */ lte(that: Point): Point; /** * Returns true if this point is greater another one * @param {fabric.Point} that * @return {Boolean} */ gt(that: Point): Point; /** * Returns true if this point is greater than or equal to another one * @param {fabric.Point} that * @return {Boolean} */ gte(that: Point): 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: Point, t: number): Point; /** * Returns distance from this point and another one * @param {fabric.Point} that * @return {Number} */ distanceFrom(that: Point): number; /** * Returns the point between this point and another one * @param {fabric.Point} that * @return {fabric.Point} */ midPointFrom(that: Point): Point; /** * Returns a new point which is the min of this and another one * @param {fabric.Point} that * @return {fabric.Point} */ min(that: Point): Point; /** * Returns a new point which is the max of this and another one * @param {fabric.Point} that * @return {fabric.Point} */ max(that: Point): 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: Point): Point; /** * Swaps x/y of this point and another point * @param {fabric.Point} that */ swap(that: Point): Point; /** * return a cloned instance of the point * @return {fabric.Point} */ clone(): Point; } interface IShadowOptions { /** * Shadow color */ color?: string; /** * Shadow blur */ blur?: number; /** * Shadow horizontal offset */ offsetX?: number; /** * Shadow vertical offset */ offsetY?: number; /** * Whether the shadow should affect stroke operations */ affectStroke?: boolean; /** * Indicates whether toObject should include default values */ includeDefaultValues?: boolean; /** * 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 * @type Boolean * @default */ nonScaling?: boolean; } 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 * @memberOf fabric.Shadow */ 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; /** * Set the given dimensions only as css dimensions */ cssOnly?: boolean; } interface IStaticCanvasOptions { /** * Background color of canvas instance. * Should be set via {@link fabric.StaticCanvas#setBackgroundColor}. * @type {(String|fabric.Pattern)} */ backgroundColor?: string | Pattern; /** * 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 * @type fabric.Image */ backgroundImage?: Image | string; /** * Overlay color of canvas instance. * Should be set via {@link fabric.StaticCanvas#setOverlayColor} * @since 1.3.9 * @type {(String|fabric.Pattern)} */ overlayColor?: string | Pattern; /** * 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 * @type fabric.Image */ overlayImage?: Image; /** * Indicates whether toObject/toDatalessObject should include default values * if set to false, takes precedence over the object value. * @type Boolean */ includeDefaultValues?: boolean; /** * Indicates whether objects' state should be saved * @type Boolean */ stateful?: boolean; /** * 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. * @type Boolean */ renderOnAddRemove?: boolean; /** * Function that determines clipping of entire canvas area * Being passed context as first argument. * If you are using code minification, ctx argument can be minified/manglied you should use * as a workaround `var ctx = arguments[0];` in the function; * See clipping canvas area in {@link https://github.com/kangax/fabric.js/wiki/FAQ} * @deprecated since 2.0.0 * @type Function */ clipTo?(context: CanvasRenderingContext2D): void; /** * Indicates whether object controls (borders/controls) are rendered above overlay image * @type Boolean */ controlsAboveOverlay?: boolean; /** * Indicates whether the browser can be scrolled when using a touchscreen and dragging on the canvas * @type Boolean */ allowTouchScrolling?: boolean; /** * Indicates whether this canvas will use image smoothing, this is on by default in browsers */ imageSmoothingEnabled?: boolean; /** * The transformation (in the format of Canvas transform) which focuses the viewport */ viewportTransform?: number[]; /** * if set to false background image is not affected by viewport transform * @since 1.6.3 * @type Boolean */ backgroundVpt?: boolean; /** * if set to false overlay image is not affected by viewport transform * @since 1.6.3 * @type Boolean */ overlayVpt?: boolean; /** * When true, canvas is scaled by devicePixelRatio for better rendering on retina screens * @type Boolean */ enableRetinaScaling?: boolean; /** * 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. * @memberOf fabric.StaticCanvas.prototype */ vptCoords?: {tl: {x: number, y: number}, tr: {x: number, y: number}, bl: {x: number, y: number}, br: {x: number, y: number}} /** * 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. * @memberOf fabric.StaticCanvas.prototype * @type Boolean */ skipOffscreen?: boolean; /** * 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 * @type fabric.Object */ clipPath?: Object; /** * When true, getSvgTransform() will apply the StaticCanvas.viewportTransform to the SVG transformation. When true, * a zoomed canvas will then produce zoomed SVG output. * @type Boolean */ svgViewportTransformation?: boolean; } export interface FreeDrawingBrush { /** * Can be any regular color value. */ color: string; /** * Brush width measured in pixels. */ width: number; } export interface StaticCanvas extends IObservable<StaticCanvas>, IStaticCanvasOptions, ICollection<StaticCanvas>, ICanvasAnimation<StaticCanvas> { } 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, options?: ICanvasOptions); _activeObject?: Object | Group; freeDrawingBrush: FreeDrawingBrush; /** * 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, 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: Point, 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: Point): Canvas; /** * Pans viewpoint relatively * @param {fabric.Point} point (position vector) to move by * @return {fabric.Canvas} instance * @chainable */ relativePan(point: Point): 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 * @private * @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[]): string; /** * Returns JSON representation of canvas * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output * @return {String} JSON string */ toJSON(propertiesToInclude?: string[]): string; /** * Returns object representation of canvas * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output * @return {Object} object representation of an instance */ toObject(propertiesToInclude?: string[]): any; /** * Returns dataless object representation of canvas * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output * @return {Object} object representation of an instance */ toDatalessObject(propertiesToInclude?: string[]): any; /** * Returns SVG representation of canvas * @param [options] Options object for SVG output * @param [reviver] Method for further parsing of svg elements, called after each fabric object converted into svg representation. * @return {String} SVG string */ toSVG(options?: IToSVGOptions, reviver?: Function): string; /** * Moves an object or the objects of a multiple selection * to the bottom of the stack of drawn objects * @param {fabric.Object} object Object to send to back * @return {fabric.Canvas} thisArg * @chainable */ sendToBack(object: Object): Canvas; /** * Moves an object or the objects of a multiple selection * to the top of the stack of drawn objects * @param {fabric.Object} object Object to send * @return {fabric.Canvas} thisArg * @chainable */ bringToFront(object: Object): Canvas; /** * Moves an object or a selection down in stack of drawn objects * An optional paramter, intersecting allowes to move the object in behind * the first intersecting object. Where intersection is calculated with * bounding box. If no intersection is found, there will not be change in the * stack. * @param {fabric.Object} object Object to send * @param {Boolean} [intersecting] If `true`, send object behind next lower intersecting object * @return {fabric.Canvas} thisArg * @chainable */ sendBackwards(object: Object, intersecting?: boolean): Canvas; /** * Moves an object or a selection up in stack of drawn objects * An optional paramter, intersecting allowes to move the object in front * of the first intersecting object. Where intersection is calculated with * bounding box. If no intersection is found, there will not be change in the * stack. * @param {fabric.Object} object Object to send * @param {Boolean} [intersecting] If `true`, send object in front of next upper intersecting object * @return {fabric.Canvas} thisArg * @chainable */ bringForward(object: Object, intersecting?: boolean): Canvas; /** * Moves an object to specified level in stack of drawn objects * @param {fabric.Object} object Object to send * @param {Number} index Position to move to * @return {fabric.Canvas} thisArg * @chainable */ moveTo(object: Object, index: number): Canvas; /** * Clears a canvas element and dispose objects * @return {fabric.Canvas} thisArg * @chainable */ dispose(): Canvas; /** * Returns a string representation of an instance * @return {String} string representation of an instance */ toString(): string; /** * @static * @type String * @default */ static EMPTY_JSON: string; /** * Provides a way to check support of some of the canvas methods * (either those of HTMLCanvasElement itself, or rendering context) * * @param {String} methodName Method to check support for; * Could be one of "setLineDash" * @return {Boolean | null} `true` if method is supported (or at least exists), * `null` if canvas element or context can not be initialized */ static supports(methodName: "getImageData" | "toDataURL" | "toDataURLWithQuality" | "setLineDash"): boolean; /** * Exports canvas element to a dataurl image. Note that when multiplier is used, cropping is scaled appropriately * @param [options] Options object */ toDataURL(options?: IDataURLOptions): string; /** * Returns JSON representation of canvas * @param [propertiesToInclude] Any properties that you might want to additionally include in the output */ static toJSON(propertiesToInclude?: string[]): string; /** * Clones canvas instance * @param [callback] Receives cloned instance as a first argument * @param [properties] Array of properties to include in the cloned canvas and children */ clone(callback?: any, properties?: string[]): void; /** * Clones canvas instance without cloning existing data. * This essentially copies canvas dimensions, clipping properties, etc. * but leaves data empty (so that you can populate it with your own) * @param [callback] Receives cloned instance as a first argument */ cloneWithoutData(callback?: any): void; /** * Populates canvas with data from the specified dataless JSON. * JSON format must conform to the one of {@link fabric.Canvas#toDatalessJSON} * @deprecated since 1.2.2 * @param {String|Object} json JSON string or object * @param {Function} callback Callback, invoked when json is parsed * and corresponding objects (e.g: {@link fabric.Image}) * are initialized * @param {Function} [reviver] Method for further parsing of JSON elements, called after each fabric object created. * @return {fabric.Canvas} instance * @chainable * @tutorial {@link http://fabricjs.com/fabric-intro-part-3#deserialization} */ loadFromDatalessJSON(json: any, callback: Function, reviver?: Function): Canvas; /** * Populates canvas with data from the specified JSON. * JSON format must conform to the one of {@link fabric.Canvas#toJSON} * @param {String|Object} json JSON string or object * @param {Function} callback Callback, invoked when json is parsed * and corresponding objects (e.g: {@link fabric.Image}) * are initialized * @param {Function} [reviver] Method for further parsing of JSON elements, called after each fabric object created. * @return {fabric.Canvas} instance */ loadFromJSON(json: any, callback: Function, reviver?: Function): Canvas; /** * Creates markup containing SVG font faces, * font URLs for font faces must be collected by developers * and are not extracted from the DOM by fabricjs * @param {Array} objects Array of fabric objects * @return {String} */ createSVGFontFacesMarkup(objects: any[]): string; /** * Creates markup containing SVG referenced elements like patterns, gradients etc. * @return {String} */ createSVGRefElementsMarkup(): string; /** * Straightens object, then rerenders canvas * @param {fabric.Object} object Object to straighten * @return {fabric.Canvas} thisArg * @chainable */ straightenObject(object: Object): Canvas; } interface ICanvasOptions extends IStaticCanvasOptions { /** * 控制器坐标 左上 */ imageControlTL?: HTMLImageElement, /** * 控制器坐标 左下 */ imageControlBL?: HTMLImageElement, /** * 控制器坐标 右上 */ imageControlTR?: HTMLImageElement, /** * 控制器坐标 右下 */ imageControlBR?: HTMLImageElement, /** * When true, objects can be transformed by one side (unproportionally) * @type Boolean */ uniScaleTransform?: boolean; /** * Indicates which key enable unproportional scaling * values: 'altKey', 'shiftKey', 'ctrlKey'. * If `null` or 'none' or any other string that is not a modifier key * feature is disabled feature disabled. * @since 1.6.2 * @type String */ uniScaleKey?: string; /** * When true, objects use center point as the origin of scale transformation. * <b>Backwards incompatibility note:</b> This property replaces "centerTransform" (Boolean). */ centeredScaling?: boolean; /** * When true, objects use center point as the origin of rotate transformation. * <b>Backwards incompatibility no