util

fabric. util

Source:

Namespaces

array
ease
object
string

Members

(static) fromArcToBeizers

Source:
Deprecated:
  • Yes
Typo of `fromArcToBeziers` kept for not breaking the api once corrected. Will be removed in fabric 5.0

(static) getElementStyle

Source:
Returns style attribute value of a given element

(static) setImageSmoothing

Source:
Since:
  • 4.0.0
setImageSmoothing sets the context imageSmoothingEnabled property. Used by canvas and by ImageObject.

Methods

(static) addClass(element, className)

Source:
Adds class to an element
Parameters:
Name Type Description
element HTMLElement Element to add class to
className String Class to add to an element

(static) addListener(element, eventName, handler)

Source:
Adds an event listener to an element
Parameters:
Name Type Description
element HTMLElement
eventName String
handler function

(static) addTransformToObject(object, transform)

Source:
given an object and a transform, apply the transform to the object. this is equivalent to change the space where the object is drawn. Adding to an object a transform that scale by 2 is like scaling it by 2. This is used when removing an object from an active selection for example.
Parameters:
Name Type Description
object fabric.Object the object you want to transform
transform Array the destination transform

(static) animate(optionsopt)

Source:
Changes value from one to another within certain period of time, invoking callbacks as value is being changed.
Parameters:
Name Type Attributes Description
options Object <optional>
Animation options
Properties
Name Type Attributes Default Description
onChange function <optional>
Callback; invoked on every value change
onComplete function <optional>
Callback; invoked when value change is completed
startValue Number <optional>
0 Starting value
endValue Number <optional>
100 Ending value
byValue Number <optional>
100 Value to modify the property by
easing function <optional>
Easing function
duration Number <optional>
500 Duration of change (in ms)
abort function <optional>
Additional function with logic. If returns true, onComplete is called.

(static) animateColor(fromColor, toColor, durationopt, optionsopt)

Source:
Changes the color from one to another within certain period of time, invoking callbacks as value is being changed.
Parameters:
Name Type Attributes Description
fromColor String The starting color in hex or rgb(a) format.
toColor String The starting color in hex or rgb(a) format.
duration Number <optional>
Duration of change (in ms).
options Object <optional>
Animation options
Properties
Name Type Attributes Description
onChange function <optional>
Callback; invoked on every value change
onComplete function <optional>
Callback; invoked when value change is completed
colorEasing function <optional>
Easing function. Note that this function only take two arguments (currentTime, duration). Thus the regular animation easing functions cannot be used.
abort function <optional>
Additional function with logic. If returns true, onComplete is called.

(static) applyTransformToObject(object, transform)

Source:
discard an object transform state and apply the one from the matrix.
Parameters:
Name Type Description
object fabric.Object the object you want to transform
transform Array the destination transform

(static) calcDimensionsMatrix(options) → {Array.<Number>}

Source:
Returns a transform matrix starting from an object of the same kind of the one returned from qrDecompose, useful also if you want to calculate some transformations from an object that is not enlived yet. is called DimensionsTransformMatrix because those properties are the one that influence the size of the resulting box of the object.
Parameters:
Name Type Description
options Object
Properties
Name Type Attributes Description
scaleX Number <optional>
scaleY Number <optional>
flipX Boolean <optional>
flipY Boolean <optional>
skewX Number <optional>
skewX Number <optional>
Returns:
transform matrix
Type
Array.<Number>

(static) calcRotateMatrix(options) → {Array.<Number>}

Source:
Returns a transform matrix starting from an object of the same kind of the one returned from qrDecompose, useful also if you want to calculate some transformations from an object that is not enlived yet
Parameters:
Name Type Description
options Object
Properties
Name Type Attributes Description
angle Number <optional>
angle in degrees
Returns:
transform matrix
Type
Array.<Number>

(static) clearFabricFontCache(fontFamilyopt)

Source:
Clear char widths cache for the given font family or all the cache if no fontFamily is specified. Use it if you know you are loading fonts in a lazy way and you are not waiting for custom fonts to load properly when adding text objects to the canvas. If a text object is added when its own font is not loaded yet, you will get wrong measurement and so wrong bounding boxes. After the font cache is cleared, either change the textObject text content or call initDimensions() to trigger a recalculation
Parameters:
Name Type Attributes Description
fontFamily String <optional>
font family to clear

(static) composeMatrix(options) → {Array.<Number>}

Source:
Returns a transform matrix starting from an object of the same kind of the one returned from qrDecompose, useful also if you want to calculate some transformations from an object that is not enlived yet
Parameters:
Name Type Description
options Object
Properties
Name Type Attributes Description
angle Number <optional>
scaleX Number <optional>
scaleY Number <optional>
flipX Boolean <optional>
flipY Boolean <optional>
skewX Number <optional>
skewX Number <optional>
translateX Number <optional>
translateY Number <optional>
Returns:
transform matrix
Type
Array.<Number>

(static) copyCanvasElement(canvas) → {CanvasElement}

Source:
Creates a canvas element that is a copy of another and is also painted
Parameters:
Name Type Description
canvas CanvasElement to copy size and content of
Returns:
initialized canvas element
Type
CanvasElement

(static) cos(angle) → {Number}

Source:
Calculate the cos of an angle, avoiding returning floats for known results
Parameters:
Name Type Description
angle Number the angle in radians or in degree
Returns:
Type
Number

(static) createCanvasElement() → {CanvasElement}

Source:
Creates canvas element
Returns:
initialized canvas element
Type
CanvasElement

(static) createClass(parentopt, propertiesopt)

Source:
Helper for creation of "classes".
Parameters:
Name Type Attributes Description
parent function <optional>
optional "Class" to inherit from
properties Object <optional>
Properties shared by all instances of this class (be careful modifying objects defined here as this would affect all instances)

(static) createImage() → {HTMLImageElement}

Source:
Creates image element (works on client and node)
Returns:
HTML image element
Type
HTMLImageElement

(static) degreesToRadians(degrees) → {Number}

Source:
Transforms degrees to radians.
Parameters:
Name Type Description
degrees Number value in degrees
Returns:
value in radians
Type
Number

(static) drawDashedLine(ctx, x, y, x2, y2, da)

Source:
Draws a dashed line between two points This method is used to draw dashed line around selection area. See dotted stroke in canvas
Parameters:
Name Type Description
ctx CanvasRenderingContext2D context
x Number start x coordinate
y Number start y coordinate
x2 Number end x coordinate
y2 Number end y coordinate
da Array dash array pattern

(static) enlivenObjects(objects, callback, namespace, reviver)

Source:
Creates corresponding fabric instances from their object representations
Parameters:
Name Type Description
objects Array Objects to enliven
callback function Callback to invoke when all objects are created
namespace String Namespace to get klass "Class" object from
reviver function Method for further parsing of object elements, called after each fabric object created.

(static) enlivenPatterns(patterns, callback)

Source:
Create and wait for loading of patterns
Parameters:
Name Type Description
patterns Array Objects to enliven
callback function Callback to invoke when all objects are created called after each fabric object created.

(static) falseFunction() → {Boolean}

Source:
Function which always returns `false`.
Returns:
Type
Boolean

(static) findScaleToCover(source, destination) → {Number}

Source:
Finds the scale for the object source to cover entirely the object destination, keeping aspect ratio intact. respect the total allowed area for the cache.
Parameters:
Name Type Description
source Object | fabric.Object
Properties
Name Type Description
height Number natural unscaled height of the object
width Number natural unscaled width of the object
destination Object | fabric.Object
Properties
Name Type Description
height Number natural unscaled height of the object
width Number natural unscaled width of the object
Returns:
scale factor to apply to source to cover destination
Type
Number

(static) findScaleToFit(source, destination) → {Number}

Source:
Finds the scale for the object source to fit inside the object destination, keeping aspect ratio intact. respect the total allowed area for the cache.
Parameters:
Name Type Description
source Object | fabric.Object
Properties
Name Type Description
height Number natural unscaled height of the object
width Number natural unscaled width of the object
destination Object | fabric.Object
Properties
Name Type Description
height Number natural unscaled height of the object
width Number natural unscaled width of the object
Returns:
scale factor to apply to source to fit into destination
Type
Number

(static) getById(id) → {HTMLElement|null}

Source:
Takes id and returns an element with that id (if one exists in a document)
Parameters:
Name Type Description
id String | HTMLElement
Returns:
Type
HTMLElement | null

(static) getElementOffset(element) → {Object}

Source:
Returns offset for a given element
Parameters:
Name Type Description
element HTMLElement Element to get offset for
Returns:
Object with "left" and "top" properties
Type
Object

(static) getKlass(type, namespace) → {Object}

Source:
Returns klass "Class" object of given namespace
Parameters:
Name Type Description
type String Type of object (eg. 'circle')
namespace String Namespace to get klass "Class" object from
Returns:
klass "Class"
Type
Object

(static) getRandomInt(min, max) → {Number}

Source:
Returns random number between 2 specified ones.
Parameters:
Name Type Description
min Number lower limit
max Number upper limit
Returns:
random value (between min and max)
Type
Number

(static) getScrollLeftTop(element) → {Object}

Source:
Returns element scroll offsets
Parameters:
Name Type Description
element HTMLElement Element to operate on
Returns:
Object with left/top values
Type
Object

(static) getSvgAttributes(type) → {Array}

Source:
Returns array of attributes for given svg that fabric parses
Parameters:
Name Type Description
type String Type of svg element (eg. 'circle')
Returns:
string names of supported attributes
Type
Array

(static) groupSVGElements(elements, optionsopt, path) → {fabric.Object|fabric.Group}

Source:
Groups SVG elements (usually those retrieved from SVG document)
Parameters:
Name Type Attributes Description
elements Array SVG elements to group
options Object <optional>
Options object
path String Value to set sourcePath to
Returns:
Type
fabric.Object | fabric.Group

(static) invertTransform(t) → {Array}

Source:
Invert transformation t
Parameters:
Name Type Description
t Array The transform
Returns:
The inverted transform
Type
Array

(static) isTransparent(ctx, x, y, tolerance)

Source:
Returns true if context has transparent pixel at specified location (taking tolerance into account)
Parameters:
Name Type Description
ctx CanvasRenderingContext2D context
x Number x coordinate
y Number y coordinate
tolerance Number Tolerance

(static) limitDimsByArea(ar, maximumArea) → {Object.x|Object.y}

Source:
Given current aspect ratio, determines the max width and height that can respect the total allowed area for the cache.
Parameters:
Name Type Description
ar Number aspect ratio
maximumArea Number Maximum area you want to achieve
Returns:
  • Limited dimensions by X
    Type
    Object.x
  • Limited dimensions by Y
    Type
    Object.y

(static) loadImage(url, callback, contextopt, crossOriginopt)

Source:
Loads image element from given url and passes it to a callback
Parameters:
Name Type Attributes Description
url String URL representing an image
callback function Callback; invoked with loaded image
context * <optional>
Context to invoke callback in
crossOrigin Object <optional>
crossOrigin value to set image element to

(static) loadImageInDom(img, callback) → {Object}

Source:
Attaches SVG image with data: URL to the dom
Parameters:
Name Type Description
img Object Image object with data:image/svg src
callback function Callback; invoked with loaded image
Returns:
DOM element (div containing the SVG image)
Type
Object

(static) makeBoundingBoxFromPoints(points, transformopt) → {Object}

Source:
Returns coordinates of points's bounding rectangle (left, top, width, height)
Parameters:
Name Type Attributes Description
points Array 4 points array
transform Array <optional>
an array of 6 numbers representing a 2x3 transform matrix
Returns:
Object with left, top, width, height properties
Type
Object

(static) makeElement(tagName, attributesopt) → {HTMLElement}

Source:
Creates specified element with specified attributes
Parameters:
Name Type Attributes Description
tagName String Type of an element to create
attributes Object <optional>
Attributes to set on an element
Returns:
Newly created element
Type
HTMLElement

(static) makeElementSelectable(element) → {HTMLElement}

Source:
Makes element selectable
Parameters:
Name Type Description
element HTMLElement Element to make selectable
Returns:
Element that was passed in
Type
HTMLElement

(static) makeElementUnselectable(element) → {HTMLElement}

Source:
Makes element unselectable
Parameters:
Name Type Description
element HTMLElement Element to make unselectable
Returns:
Element that was passed in
Type
HTMLElement

(static) matrixToSVG(transform) → {String|Object.y}

Source:
given an array of 6 number returns something like `"matrix(...numbers)"`
Parameters:
Name Type Description
transform Array an array with 6 numbers
Returns:
  • transform matrix for svg
    Type
    String
  • Limited dimensions by Y
    Type
    Object.y

(static) multiplyTransformMatrices(a, b, is2x2) → {Array}

Source:
Multiply matrix A by matrix B to nest transformations
Parameters:
Name Type Description
a Array First transformMatrix
b Array Second transformMatrix
is2x2 Boolean flag to multiply matrices as 2x2 matrices
Returns:
The product of the two transform matrices
Type
Array

(static) parsePreserveAspectRatioAttribute(attribute) → {Object}

Source:
Parse preserveAspectRatio attribute from element
Parameters:
Name Type Description
attribute string to be parsed
Returns:
an object containing align and meetOrSlice attribute
Type
Object

(static) parseUnit(value, fontSize) → {Number|String}

Source:
Converts from attribute value to pixel value if applicable. Returns converted pixels or original value not converted.
Parameters:
Name Type Description
value Number | String number to operate on
fontSize Number
Returns:
Type
Number | String

(static) populateWithProperties(source, destination) → {Array}

Source:
Populates an object with properties of another object
Parameters:
Name Type Description
source Object Source object
destination Object Destination object
Returns:
properties Properties names to include
Type
Array

(static) qrDecompose(a) → {Object}

Source:
Decomposes standard 2x3 matrix into transform components
Parameters:
Name Type Description
a Array transformMatrix
Returns:
Components of transform
Type
Object

(static) radiansToDegrees(radians) → {Number}

Source:
Transforms radians to degrees.
Parameters:
Name Type Description
radians Number value in radians
Returns:
value in degrees
Type
Number

(static) removeFromArray(array, value) → {Array}

Source:
Removes value from an array. Presence of value (and its position in an array) is determined via `Array.prototype.indexOf`
Parameters:
Name Type Description
array Array
value *
Returns:
original array
Type
Array

(static) removeListener(element, eventName, handler)

Source:
Removes an event listener from an element
Parameters:
Name Type Description
element HTMLElement
eventName String
handler function

(static) removeTransformFromObject(object, transform)

Source:
given an object and a transform, apply the inverse transform to the object, this is equivalent to remove from that object that transformation, so that added in a space with the removed transform, the object will be the same as before. Removing from an object a transform that scale by 2 is like scaling it by 1/2. Removing from an object a transfrom that rotate by 30deg is like rotating by 30deg in the opposite direction. This util is used to add objects inside transformed groups or nested groups.
Parameters:
Name Type Description
object fabric.Object the object you want to transform
transform Array the destination transform

(static) request(url, optionsopt) → {XMLHttpRequest}

Source:
Cross-browser abstraction for sending XMLHttpRequest
Parameters:
Name Type Attributes Description
url String URL to send XMLHttpRequest to
options Object <optional>
Options object
Properties
Name Type Attributes Default Description
method String <optional>
"GET"
parameters String <optional>
parameters to append to url in GET or in body
body String <optional>
body to send with POST or PUT request
onComplete function Callback to invoke when request is completed
Returns:
request
Type
XMLHttpRequest

(static) requestAnimFrame(callback, element)

Source:
requestAnimationFrame polyfill based on http://paulirish.com/2011/requestanimationframe-for-smart-animating/ In order to get a precise start time, `requestAnimFrame` should be called as an entry into the method
Parameters:
Name Type Description
callback function Callback to invoke
element DOMElement optional Element to associate with animation

(static) resetObjectTransform(target)

Source:
reset an object transform state to neutral. Top and left are not accounted for
Parameters:
Name Type Description
target fabric.Object object to transform

(static) resolveNamespace(namespace) → {Object}

Source:
Returns object of given namespace
Parameters:
Name Type Description
namespace String Namespace string e.g. 'fabric.Image.filter' or 'fabric'
Returns:
Object for given namespace (default fabric)
Type
Object

(static) rotatePoint(point, origin, radians) → {fabric.Point}

Source:
Rotates `point` around `origin` with `radians`
Parameters:
Name Type Description
point fabric.Point The point to rotate
origin fabric.Point The origin of the rotation
radians Number The radians of the angle for the rotation
Returns:
The new rotated point
Type
fabric.Point

(static) rotateVector(vector, radians) → {Object}

Source:
Rotates `vector` with `radians`
Parameters:
Name Type Description
vector Object The vector to rotate (x and y)
radians Number The radians of the angle for the rotation
Returns:
The new rotated point
Type
Object

(static) saveObjectTransform(target) → {Object}

Source:
Extract Object transform values
Parameters:
Name Type Description
target fabric.Object object to read from
Returns:
Components of transform
Type
Object

(static) setStyle(element, styles) → {HTMLElement}

Source:
Cross-browser wrapper for setting element's style
Parameters:
Name Type Description
element HTMLElement
styles Object
Returns:
Element that was passed as a first argument
Type
HTMLElement

(static) sin(angle) → {Number}

Source:
Calculate the sin of an angle, avoiding returning floats for known results
Parameters:
Name Type Description
angle Number the angle in radians or in degree
Returns:
Type
Number

(static) sizeAfterTransform(width, height, options) → {Object.x|Object.y}

Source:
given a width and height, return the size of the bounding box that can contains the box with width/height with applied transform described in options. Use to calculate the boxes around objects for controls.
Parameters:
Name Type Description
width Number
height Number
options Object
Properties
Name Type Description
scaleX Number
scaleY Number
skewX Number
skewY Number
Returns:
  • width of containing
    Type
    Object.x
  • height of containing
    Type
    Object.y

(static) toArray(arrayLike) → {Array}

Source:
Converts an array-like object (e.g. arguments or NodeList) to an array
Parameters:
Name Type Description
arrayLike Object
Returns:
Type
Array

(static) toDataURL(canvasEl, format, quality) → {String}

Source:
since 2.6.0 moved from canvas instance to utility.
Parameters:
Name Type Description
canvasEl CanvasElement to copy size and content of
format String 'jpeg' or 'png', in some browsers 'webp' is ok too
quality Number <= 1 and > 0
Returns:
data url
Type
String

(static) toFixed(number, fractionDigits) → {Number}

Source:
A wrapper around Number#toFixed, which contrary to native method returns number, not string.
Parameters:
Name Type Description
number Number | String number to operate on
fractionDigits Number number of fraction digits to "leave"
Returns:
Type
Number

(static) transformPoint(p, t, ignoreOffsetopt) → {fabric.Point}

Source:
Apply transform t to point p
Parameters:
Name Type Attributes Description
p fabric.Point The point to transform
t Array The transform
ignoreOffset Boolean <optional>
Indicates that the offset should not be applied
Returns:
The transformed point
Type
fabric.Point

(static) wrapElement(element, wrapper, attributesopt) → {HTMLElement}

Source:
Wraps element with another element
Parameters:
Name Type Attributes Description
element HTMLElement Element to wrap
wrapper HTMLElement | String Element to wrap with
attributes Object <optional>
Attributes to set on a wrapper
Returns:
wrapper
Type
HTMLElement