Namespace: util

fabric.util

Source:

Namespaces

array
ease
object
string

Members

(static) getElementStyle

Returns style attribute value of a given element
Source:

(static) setImageSmoothing

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

Methods

(static) addClass(element, className)

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

(static) addListener(element, eventName, handler)

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

(static) addTransformToObject(object, transform)

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
Source:

(static) animate(optionsopt) → {CancelFunction}

Changes value from one to another within certain period of time, invoking callbacks as value is being changed.
Parameters:
Name Type Attributes Description
options AnimationOptions <optional>
Animation options
Source:
Returns:
cancel function
Type
CancelFunction

(static) animateColor(fromColor, toColor, durationopt, optionsopt) → {function}

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.
Source:
Returns:
abort function
Type
function

(static) applyTransformToObject(object, transform)

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
Source:

(static) calcAngleBetweenVectors(a, b)

Calculates angle between 2 vectors using dot product
Parameters:
Name Type Description
a Point
b Point
Source:
Returns:
the angle in radian between the vectors

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

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>
skewY Number <optional>
Source:
Returns:
transform matrix
Type
Array.<Number>

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

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
Source:
Returns:
transform matrix
Type
Array.<Number>

(static) clearFabricFontCache(fontFamilyopt)

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
Source:

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

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>
Source:
Returns:
transform matrix
Type
Array.<Number>

(static) copyCanvasElement(canvas) → {CanvasElement}

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
Source:
Returns:
initialized canvas element
Type
CanvasElement

(static) cos(angle) → {Number}

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
Source:
Returns:
Type
Number

(static) createCanvasElement() → {CanvasElement}

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

(static) createClass(parentopt, propertiesopt)

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)
Source:

(static) createImage() → {HTMLImageElement}

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

(static) degreesToRadians(degrees) → {Number}

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

(static) enlivenObjectEnlivables(object, contextopt)

Creates corresponding fabric instances residing in an object, e.g. `clipPath`
Parameters:
Name Type Attributes Description
object Object
context Object <optional>
assign enlived props to this object (pass null to skip this)
Source:
See:

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

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.
Source:

(static) enlivenPatterns(patterns, callback)

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.
Source:

(static) falseFunction() → {Boolean}

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

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

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
Source:
Returns:
scale factor to apply to source to cover destination
Type
Number

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

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
Source:
Returns:
scale factor to apply to source to fit into destination
Type
Number

(static) getBisector(A, B, C) → {Object}

Parameters:
Name Type Description
A Point
B Point
C Point
Source:
Returns:
vector representing the bisector of A and A's angle
Type
Object

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

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

(static) getElementOffset(element) → {Object}

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

(static) getHatVector(v) → {Point}

Parameters:
Name Type Description
v Point
Source:
Returns:
vector representing the unit vector of pointing to the direction of `v`
Type
Point

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

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
Source:
Returns:
klass "Class"
Type
Object

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

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

(static) getScrollLeftTop(element) → {Object}

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

(static) getSvgAttributes(type) → {Array}

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

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

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
Source:
Returns:
Type
fabric.Object | fabric.Group

(static) invertTransform(t) → {Array}

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

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

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
Source:

(static) joinPath(pathData) → {String}

Join path commands to go back to svg format
Parameters:
Name Type Description
pathData Array fabricJS parsed path commands
Source:
Returns:
joined path 'M 0 0 L 20 30'
Type
String

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

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
Source:
Returns:
  • Limited dimensions by X
    Type
    Object.x
  • Limited dimensions by Y
    Type
    Object.y

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

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
Source:

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

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
Source:
Returns:
DOM element (div containing the SVG image)
Type
Object

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

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
Source:
Returns:
Object with left, top, width, height properties
Type
Object

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

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
Source:
Returns:
Newly created element
Type
HTMLElement

(static) makeElementSelectable(element) → {HTMLElement}

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

(static) makeElementUnselectable(element) → {HTMLElement}

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

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

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

(static) mergeClipPaths(c1, c2) → {fabric.Object}

Merges 2 clip paths into one visually equal clip path **IMPORTANT**:\ Does **NOT** clone the arguments, clone them proir if necessary. Creates a wrapper (group) that contains one clip path and is clipped by the other so content is kept where both overlap. Use this method if both the clip paths may have nested clip paths of their own, so assigning one to the other's clip path property is not possible. In order to handle the `inverted` property we follow logic described in the following cases:\ **(1)** both clip paths are inverted - the clip paths pass the inverted prop to the wrapper and loose it themselves.\ **(2)** one is inverted and the other isn't - the wrapper shouldn't become inverted and the inverted clip path must clip the non inverted one to produce an identical visual effect.\ **(3)** both clip paths are not inverted - wrapper and clip paths remain unchanged.
Parameters:
Name Type Description
c1 fabric.Object
c2 fabric.Object
Source:
Returns:
merged clip path
Type
fabric.Object

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

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
Source:
Returns:
The product of the two transform matrices
Type
Array

(static) parsePreserveAspectRatioAttribute(attribute) → {Object}

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

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

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
Source:
Returns:
Type
Number | String

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

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

(static) projectStrokeOnPoints(points, options, openPathopt) → {Array.<fabric.Point>}

Project stroke width on points returning 2 projections for each point as follows: - `miter`: 2 points corresponding to the outer boundary and the inner boundary of stroke. - `bevel`: 2 points corresponding to the bevel boundaries, tangent to the bisector. - `round`: same as `bevel` Used to calculate object's bounding box
Parameters:
Name Type Attributes Description
points Array.<Point>
options Object
Properties
Name Type Description
strokeWidth number
strokeLineJoin 'miter' | 'bevel' | 'round'
strokeMiterLimit number https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-miterlimit
strokeUniform boolean
scaleX number
scaleY number
openPath boolean <optional>
whether the shape is open or not, affects the calculations of the first and last points
Source:
Returns:
array of size 2n/4n of all suspected points
Type
Array.<fabric.Point>

(static) qrDecompose(a) → {Object}

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

(static) radiansToDegrees(radians) → {Number}

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

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

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 *
Source:
Returns:
original array
Type
Array

(static) removeListener(element, eventName, handler)

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

(static) removeTransformFromObject(object, transform)

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
Source:

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

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
Source:
Returns:
request
Type
XMLHttpRequest

(static) requestAnimFrame(callback, element)

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
Source:

(static) resetObjectTransform(target)

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

(static) resolveNamespace(namespace) → {Object}

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

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

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
Source:
Returns:
The new rotated point
Type
fabric.Point

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

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
Source:
Returns:
The new rotated point
Type
Object

(static) saveObjectTransform(target) → {Object}

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

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

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

(static) sin(angle) → {Number}

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
Source:
Returns:
Type
Number

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

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
Source:
Returns:
  • width of containing
    Type
    Object.x
  • height of containing
    Type
    Object.y

(static) toArray(arrayLike) → {Array}

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

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

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
Source:
Returns:
data url
Type
String

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

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"
Source:
Returns:
Type
Number

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

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
Source:
Returns:
The transformed point
Type
fabric.Point

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

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
Source:
Returns:
wrapper
Type
HTMLElement

Type Definitions

Point

Creates a vetor from points represented as a point
Type:
  • Object
Properties:
Name Type Description
x number
y number
Source: