Canvas

fabric. Canvas

new Canvas()

Source:
Tutorials:
See:
Canvas class
Fires:
  • object:modified at the end of a transform or any change when statefull is true
  • object:rotating while an object is being rotated from the control
  • object:scaling while an object is being scaled by controls
  • object:moving while an object is being dragged
  • object:skewing while an object is being skewed from the controls
  • before:transform before a transform is is started
  • before:selection:cleared
  • selection:cleared
  • selection:updated
  • selection:created
  • path:created after a drawing operation ends and the path is added
  • mouse:down
  • mouse:move
  • mouse:up
  • mouse:down:before on mouse down,event: before the inner fabric logic runs
  • mouse:move:before on mouse move,event: before the inner fabric logic runs
  • mouse:up:before on mouse up,event: before the inner fabric logic runs
  • mouse:over
  • mouse:out
  • mouse:dblclick whenever a native dbl click event fires on the canvas.
  • event:dragover
  • event:dragenter
  • event:dragleave
  • event:drop
  • after:render at the end of the render process,event: receives the context in the callback
  • before:render at start the render process, receives the context in the callback the following events are deprecated:event:
  • object:rotated at the end of a rotation transform
  • object:scaled at the end of a scale transform
  • object:moved at the end of translation transform
  • object:skewed at the end of a skew transform

Extends

Members

allowTouchScrolling :Boolean

Source:
Inherited From:
Indicates whether the browser can be scrolled when using a touchscreen and dragging on the canvas
Type:
  • Boolean

altActionKey :String

Source:
Since:
  • 1.6.2
Default Value:
  • shiftKey
Indicates which key enable alternate action on corner values: 'altKey', 'shiftKey', 'ctrlKey'. If `null` or 'none' or any other string that is not a modifier key feature is disabled feature disabled.
Type:
  • String

altSelectionKey :null|String

Source:
Since:
  • 1.6.5
Indicates which key enable alternative selection in case of target overlapping with active object values: 'altKey', 'shiftKey', 'ctrlKey'. For a series of reason that come from the general expectations on how things should work, this feature works only for preserveObjectStacking true. If `null` or 'none' or any other string that is not a modifier key feature is disabled.
Type:
  • null | String

backgroundColor :String|fabric.Pattern

Source:
Inherited From:
Background color of canvas instance. Should be set via fabric.StaticCanvas#setBackgroundColor.
Type:

backgroundImage :fabric.Image

Source:
Inherited From:
Background image of canvas instance. 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:

backgroundVpt :Boolean

Source:
Since:
  • 1.6.3
Inherited From:
Default Value:
  • true
if set to false background image is not affected by viewport transform
Type:
  • Boolean

centeredKey :String

Source:
Since:
  • 1.6.2
Default Value:
  • altKey
Indicates which key enable centered Transform values: 'altKey', 'shiftKey', 'ctrlKey'. If `null` or 'none' or any other string that is not a modifier key feature is disabled feature disabled.
Type:
  • String

centeredRotation :Boolean

Source:
Since:
  • 1.3.4
When true, objects use center point as the origin of rotate transformation. Backwards incompatibility note: This property replaces "centerTransform" (Boolean).
Type:
  • Boolean

centeredScaling :Boolean

Source:
Since:
  • 1.3.4
When true, objects use center point as the origin of scale transformation. Backwards incompatibility note: This property replaces "centerTransform" (Boolean).
Type:
  • Boolean

clipPath :fabric.Object

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

containerClass :String

Source:
Default Value:
  • canvas-container
Default element class that's given to wrapper (div) element of canvas
Type:
  • String

controlsAboveOverlay :Boolean

Source:
Inherited From:
Indicates whether object controls (borders/controls) are rendered above overlay image
Type:
  • Boolean

defaultCursor :String

Source:
Default Value:
  • default
Default cursor value used for the entire canvas
Type:
  • String

enableRetinaScaling :Boolean

Source:
Inherited From:
Default Value:
  • true
When true, canvas is scaled by devicePixelRatio for better rendering on retina screens
Type:
  • Boolean

fireMiddleClick :Boolean

Source:
Since:
  • 1.7.8
Indicates if the canvas can fire middle click events
Type:
  • Boolean

fireRightClick :Boolean

Source:
Since:
  • 1.6.5
Indicates if the canvas can fire right click events
Type:
  • Boolean

freeDrawingCursor :String

Source:
Default Value:
  • crosshair
Cursor value used during free drawing
Type:
  • String

FX_DURATION :Number

Source:
Inherited From:
Default Value:
  • 500
Animation duration (in ms) for fx* methods
Type:
  • Number

hoverCursor :String

Source:
Default Value:
  • move
Default cursor value used when hovering over an object on canvas
Type:
  • String

imageSmoothingEnabled :Boolean

Source:
Inherited From:
Default Value:
  • true
Indicates whether this canvas will use image smoothing, this is on by default in browsers
Type:
  • Boolean

includeDefaultValues :Boolean

Source:
Inherited From:
Default Value:
  • true
Indicates whether toObject/toDatalessObject should include default values if set to false, takes precedence over the object value.
Type:
  • Boolean

interactive :Boolean

Source:
Default Value:
  • true
Indicates that canvas is interactive. This property should not be changed.
Type:
  • Boolean

isDrawingMode :Boolean

Source:
Tutorials:
When true, mouse events on canvas (mousedown/mousemove/mouseup) result in free drawing. After mousedown, mousemove creates a shape, and then mouseup finalizes it and adds an instance of `fabric.Path` onto canvas.
Type:
  • Boolean

moveCursor :String

Source:
Default Value:
  • move
Default cursor value used when moving an object on canvas
Type:
  • String

notAllowedCursor :String

Source:
Since:
  • 2.0.0
Default Value:
  • not-allowed
Cursor value used for disabled elements ( corners with disabled action )
Type:
  • String

overlayColor :String|fabric.Pattern

Source:
Since:
  • 1.3.9
Inherited From:
Overlay color of canvas instance. Should be set via fabric.StaticCanvas#setOverlayColor
Type:

overlayImage :fabric.Image

Source:
Inherited From:
Overlay image of canvas instance. 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:

overlayVpt :Boolean

Source:
Since:
  • 1.6.3
Inherited From:
Default Value:
  • true
if set to false overlya image is not affected by viewport transform
Type:
  • Boolean

perPixelTargetFind :Boolean

Source:
When true, object detection happens on per-pixel basis rather than on per-bounding-box
Type:
  • Boolean

preserveObjectStacking :Boolean

Source:
Indicates whether objects should remain in current stack position when selected. When false objects are brought to top and rendered as part of the selection group
Type:
  • Boolean

renderOnAddRemove :Boolean

Source:
Inherited From:
Default Value:
  • true
Indicates whether fabric.Collection.add, fabric.Collection.insertAt and fabric.Collection.remove, fabric.StaticCanvas.moveTo, 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

rotationCursor :String

Source:
Default Value:
  • crosshair
Cursor value used for rotation point
Type:
  • String

selection :Boolean

Source:
Default Value:
  • true
Indicates whether group selection should be enabled
Type:
  • Boolean

selectionBorderColor :String

Source:
Default Value:
  • rgba(255, 255, 255, 0.3)
Color of the border of selection (usually slightly darker than color of selection itself)
Type:
  • String

selectionColor :String

Source:
Default Value:
  • rgba(100, 100, 255, 0.3)
Color of selection
Type:
  • String

selectionDashArray :Array

Source:
Default dash array pattern If not empty the selection border is dashed
Type:
  • Array

selectionFullyContained :Boolean

Source:
Select only shapes that are fully contained in the dragged selection rectangle.
Type:
  • Boolean

selectionKey :String|Array

Source:
Since:
  • 1.6.2
Default Value:
  • shiftKey
Indicates which key or keys enable multiple click selection Pass value as a string or array of strings values: 'altKey', 'shiftKey', 'ctrlKey'. If `null` or empty or containing any other string that is not a modifier key feature is disabled.
Type:
  • String | Array

selectionLineWidth :Number

Source:
Default Value:
  • 1
Width of a line used in object/group selection
Type:
  • Number

skipOffscreen :Boolean

Source:
Inherited From:
Default Value:
  • true
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.
Type:
  • Boolean

skipTargetFind :Boolean

Source:
When true, target detection is skipped. Target detection will return always undefined. click selection won't work anymore, events will fire with no targets. if something is selected before setting it to true, it will be deselected at the first click. area selection will still work. check the `selection` property too. if you deactivate both, you should look into staticCanvas.
Type:
  • Boolean

snapAngle :Number

Source:
Since:
  • 1.6.7
Indicates the angle that an object will lock to while rotating.
Type:
  • Number

snapThreshold :null|Number

Source:
Since:
  • 1.6.7
Indicates the distance from the snapAngle the rotation will lock to the snapAngle. When `null`, the snapThreshold will default to the snapAngle.
Type:
  • null | Number

stateful :Boolean

Source:
Inherited From:
Indicates whether objects' state should be saved
Type:
  • Boolean

stopContextMenu :Boolean

Source:
Since:
  • 1.6.5
Indicates if the right click on canvas can output the context menu or not
Type:
  • Boolean

svgViewportTransformation :Boolean

Source:
Inherited From:
Default Value:
  • true
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

targetFindTolerance :Number

Source:
Number of pixels around target pixel to tolerate (consider active) during object detection
Type:
  • Number

targets :Array.<fabric.Object>

Source:
Keep track of the subTargets for Mouse Events
Type:

uniformScaling :Boolean

Source:
Since:
  • fabric 4.0 // changed name and default value
Default Value:
  • true
When true, objects can be transformed by one side (unproportionally) when dragged on the corners that normally would not do that.
Type:
  • Boolean

uniScaleKey :String

Source:
Since:
  • 1.6.2
Default Value:
  • shiftKey
Indicates which key switches uniform scaling. values: 'altKey', 'shiftKey', 'ctrlKey'. If `null` or 'none' or any other string that is not a modifier key feature is disabled. totally wrong named. this sounds like `uniform scaling` if Canvas.uniformScaling is true, pressing this will set it to false and viceversa.
Type:
  • String

viewportTransform :Array

Source:
Inherited From:
The transformation (in the format of Canvas transform) which focuses the viewport
Type:
  • Array

vptCoords

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

Methods

__onMouseWheel(e)

Source:
Method that defines actions when an Event Mouse Wheel
Parameters:
Name Type Description
e Event Event object fired on mouseup

_chooseObjectsToRender() → {Array}

Source:
Divides objects in two groups, one to render immediately and one to render as activeGroup.
Returns:
objects to render immediately and pushes the other in the activeGroup.
Type
Array

_setCursorFromEvent(e, target)

Source:
Sets the cursor depending on where the canvas is being hovered. Note: very buggy in Opera
Parameters:
Name Type Description
e Event Event object
target Object Object that the mouse is hovering, if so.

absolutePan(point) → {fabric.Canvas}

Source:
Inherited From:
Pan viewport so as to place point at top left corner of canvas
Parameters:
Name Type Description
point fabric.Point to move to
Returns:
instance
Type
fabric.Canvas

add(…object) → {Self}

Source:
Inherited From:
Mixes In:
Adds objects to collection, Canvas or Group, then renders canvas (if `renderOnAddRemove` is not `false`). in case of Group no changes to bounding box are made. Objects should be instances of (or inherit from) fabric.Object Use of this function is highly discouraged for groups. you can add a bunch of objects with the add method but then you NEED to run a addWithUpdate call for the Group class or position/bbox will be wrong.
Parameters:
Name Type Attributes Description
object fabric.Object <repeatable>
Zero or more fabric instances
Returns:
thisArg
Type
Self

bringForward(object, intersectingopt) → {fabric.Canvas}

Source:
Inherited From:
Moves an object or a selection up in stack of drawn objects An optional parameter, intersecting allows 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.
Parameters:
Name Type Attributes Description
object fabric.Object Object to send
intersecting Boolean <optional>
If `true`, send object in front of next upper intersecting object
Returns:
thisArg
Type
fabric.Canvas

bringToFront(object) → {fabric.Canvas}

Source:
Inherited From:
Moves an object or the objects of a multiple selection to the top of the stack of drawn objects
Parameters:
Name Type Description
object fabric.Object Object to send
Returns:
thisArg
Type
fabric.Canvas

calcOffset() → {fabric.Canvas}

Source:
Inherited From:
Calculates canvas element offset relative to the document This method is also attached as "resize" event handler of window
Returns:
instance
Type
fabric.Canvas

calcViewportBoundaries() → {Object}

Source:
Inherited From:
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 )
Returns:
points.tl
Type
Object

centerObject(object) → {fabric.Canvas}

Source:
Inherited From:
Centers object vertically and horizontally in the canvas
Parameters:
Name Type Description
object fabric.Object Object to center vertically and horizontally
Returns:
thisArg
Type
fabric.Canvas

centerObjectH(object) → {fabric.Canvas}

Source:
Inherited From:
Centers object horizontally in the canvas
Parameters:
Name Type Description
object fabric.Object Object to center horizontally
Returns:
thisArg
Type
fabric.Canvas

centerObjectV(object) → {fabric.Canvas}

Source:
Inherited From:
Centers object vertically in the canvas
Parameters:
Name Type Description
object fabric.Object Object to center vertically
Returns:
thisArg
Type
fabric.Canvas

clear() → {fabric.Canvas}

Source:
Overrides:
Clears all contexts (background, main, top) of an instance
Returns:
thisArg
Type
fabric.Canvas

clearContext(ctx) → {fabric.Canvas}

Source:
Inherited From:
Clears specified context of canvas element
Parameters:
Name Type Description
ctx CanvasRenderingContext2D Context to clear
Returns:
thisArg
Type
fabric.Canvas

clone(callbackopt, propertiesopt)

Source:
Inherited From:
Clones canvas instance
Parameters:
Name Type Attributes Description
callback Object <optional>
Receives cloned instance as a first argument
properties Array <optional>
Array of properties to include in the cloned canvas and children

cloneWithoutData(callbackopt)

Source:
Inherited From:
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)
Parameters:
Name Type Attributes Description
callback Object <optional>
Receives cloned instance as a first argument

complexity() → {Number}

Source:
Inherited From:
Mixes In:
Returns number representation of a collection complexity
Returns:
complexity
Type
Number

contains(object) → {Boolean}

Source:
Inherited From:
Mixes In:
Returns true if collection contains an object
Parameters:
Name Type Description
object Object Object to check against
Returns:
`true` if collection contains an object
Type
Boolean

createSVGFontFacesMarkup(objects) → {String}

Source:
Inherited From:
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
Parameters:
Name Type Description
objects Array Array of fabric objects
Returns:
Type
String

createSVGRefElementsMarkup() → {String}

Source:
Inherited From:
Creates markup containing SVG referenced elements like patterns, gradients etc.
Returns:
Type
String

discardActiveObject(e) → {fabric.Canvas}

Source:
Discards currently active object and fire events. If the function is called by fabric as a consequence of a mouse event, the event is passed as a parameter and sent to the fire function for the custom events. When used as a method the e param does not have any application.
Parameters:
Name Type Description
e event
Returns:
thisArg
Type
fabric.Canvas

dispose() → {fabric.Canvas}

Source:
Overrides:
Clears a canvas element and removes all event listeners
Returns:
thisArg
Type
fabric.Canvas

drawClipPathOnCanvas(ctx)

Source:
Inherited From:
Paint the cached clipPath on the lowerCanvasEl
Parameters:
Name Type Description
ctx CanvasRenderingContext2D Context to render on

drawControls(ctx)

Source:
Draws objects' controls (borders/controls)
Parameters:
Name Type Description
ctx CanvasRenderingContext2D Context to render controls on

findTarget(e, skipGroup) → {fabric.Object}

Source:
Method that determines what object we are clicking on the skipGroup parameter is for internal use, is needed for shift+click action 11/09/2018 TODO: would be cool if findTarget could discern between being a full target or the outside part of the corner.
Parameters:
Name Type Description
e Event mouse event
skipGroup Boolean when true, activeGroup is skipped and only objects are traversed through
Returns:
the target found
Type
fabric.Object

fire(eventName, optionsopt) → {Self}

Source:
Inherited From:
Mixes In:
Fires event with an optional options object
Parameters:
Name Type Attributes Description
eventName String Event name to fire
options Object <optional>
Options object
Returns:
thisArg
Type
Self

forEachObject(callback, context) → {Self}

Source:
Inherited From:
Mixes In:
Executes given function for each object in this group
Parameters:
Name Type Description
callback function Callback invoked with current object as first argument, index - as second and an array of all objects - as third. Callback is invoked in a context of Global Object (e.g. `window`) when no `context` argument is given
context Object Context (aka thisObject)
Returns:
thisArg
Type
Self

fxCenterObjectH(object, callbacksopt) → {fabric.Canvas}

Source:
Inherited From:
Centers object horizontally with animation.
Parameters:
Name Type Attributes Description
object fabric.Object Object to center
callbacks Object <optional>
Callbacks object with optional "onComplete" and/or "onChange" properties
Properties
Name Type Attributes Description
onComplete function <optional>
Invoked on completion
onChange function <optional>
Invoked on every step of animation
Returns:
thisArg
Type
fabric.Canvas

fxCenterObjectV(object, callbacksopt) → {fabric.Canvas}

Source:
Inherited From:
Centers object vertically with animation.
Parameters:
Name Type Attributes Description
object fabric.Object Object to center
callbacks Object <optional>
Callbacks object with optional "onComplete" and/or "onChange" properties
Properties
Name Type Attributes Description
onComplete function <optional>
Invoked on completion
onChange function <optional>
Invoked on every step of animation
Returns:
thisArg
Type
fabric.Canvas

fxRemove(object, callbacksopt) → {fabric.Canvas}

Source:
Inherited From:
Same as `fabric.Canvas#remove` but animated
Parameters:
Name Type Attributes Description
object fabric.Object Object to remove
callbacks Object <optional>
Callbacks object with optional "onComplete" and/or "onChange" properties
Properties
Name Type Attributes Description
onComplete function <optional>
Invoked on completion
onChange function <optional>
Invoked on every step of animation
Returns:
thisArg
Type
fabric.Canvas

fxStraightenObject(object) → {fabric.Canvas}

Source:
Inherited From:
Same as fabric.Canvas.prototype.straightenObject, but animated
Parameters:
Name Type Description
object fabric.Object Object to straighten
Returns:
thisArg
Type
fabric.Canvas

getActiveObject() → {fabric.Object}

Source:
Returns currently active object
Returns:
active object
Type
fabric.Object

getActiveObjects() → {fabric.Object}

Source:
Returns an array with the current selected objects
Returns:
active object
Type
fabric.Object

getCenter() → {Object}

Source:
Inherited From:
Returns coordinates of a center of canvas. Returned value is an object with top and left properties
Returns:
object with "top" and "left" number values
Type
Object

getContext() → {CanvasRenderingContext2D}

Source:
Inherited From:
Returns context of canvas where objects are drawn
Returns:
Type
CanvasRenderingContext2D

getElement() → {HTMLCanvasElement}

Source:
Inherited From:
Returns <canvas> element corresponding to this instance
Returns:
Type
HTMLCanvasElement

getHeight() → {Number}

Source:
Inherited From:
Returns canvas height (in px)
Returns:
Type
Number

getObjects(typeopt) → {Array}

Source:
Inherited From:
Mixes In:
Returns an array of children objects of this instance Type parameter introduced in 1.3.10 since 2.3.5 this method return always a COPY of the array;
Parameters:
Name Type Attributes Description
type String <optional>
When specified, only objects of this type are returned
Returns:
Type
Array

getPointer(e, ignoreZoom) → {Object}

Source:
Returns pointer coordinates relative to canvas. Can return coordinates with or without viewportTransform. ignoreZoom false gives back coordinates that represent the point clicked on canvas element. ignoreZoom true gives back coordinates after being processed by the viewportTransform ( sort of coordinates of what is displayed on the canvas where you are clicking. ignoreZoom true = HTMLElement coordinates relative to top,left ignoreZoom false, default = fabric space coordinates, the same used for shape position To interact with your shapes top and left you want to use ignoreZoom true most of the time, while ignoreZoom false will give you coordinates compatible with the object.oCoords system. of the time.
Parameters:
Name Type Description
e Event
ignoreZoom Boolean
Returns:
object with "x" and "y" number values
Type
Object

getSelectionContext() → {CanvasRenderingContext2D}

Source:
Returns context of canvas where object selection is drawn
Returns:
Type
CanvasRenderingContext2D

getSelectionElement() → {HTMLCanvasElement}

Source:
Returns <canvas> element on which object selection is drawn
Returns:
Type
HTMLCanvasElement

getVpCenter() → {fabric.Point}

Source:
Inherited From:
Calculate the point in canvas that correspond to the center of actual viewport.
Returns:
vpCenter, viewport center
Type
fabric.Point

getWidth() → {Number}

Source:
Inherited From:
Returns canvas width (in px)
Returns:
Type
Number

getZoom() → {Number}

Source:
Inherited From:
Returns canvas zoom level
Returns:
Type
Number

initialize(el, optionsopt) → {Object}

Source:
Overrides:
Constructor
Parameters:
Name Type Attributes Description
el HTMLElement | String <canvas> element to initialize instance on
options Object <optional>
Options object
Returns:
thisArg
Type
Object

insertAt(object, index, nonSplicing) → {Self}

Source:
Inherited From:
Mixes In:
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 Use of this function is highly discouraged for groups. you can add a bunch of objects with the insertAt method but then you NEED to run a addWithUpdate call for the Group class or position/bbox will be wrong.
Parameters:
Name Type Description
object Object Object to insert
index Number Index to insert object at
nonSplicing Boolean When `true`, no splicing (shifting) of objects occurs
Returns:
thisArg
Type
Self

isEmpty() → {Boolean}

Source:
Inherited From:
Mixes In:
Returns true if collection contains no objects
Returns:
true if collection is empty
Type
Boolean

isTargetTransparent(target, x, y) → {Boolean}

Source:
Returns true if object is transparent at a certain location
Parameters:
Name Type Description
target fabric.Object Object to check
x Number Left coordinate
y Number Top coordinate
Returns:
Type
Boolean

item(index) → {Self}

Source:
Inherited From:
Mixes In:
Returns object at specified index
Parameters:
Name Type Description
index Number
Returns:
thisArg
Type
Self

loadFromJSON(json, callback, reviveropt) → {fabric.Canvas}

Source:
Inherited From:
Tutorials:
See:
Populates canvas with data from the specified JSON. JSON format must conform to the one of fabric.Canvas#toJSON
Examples

loadFromJSON

canvas.loadFromJSON(json, canvas.renderAll.bind(canvas));

loadFromJSON with reviver

canvas.loadFromJSON(json, canvas.renderAll.bind(canvas), function(o, object) {
  // `o` = json object
  // `object` = fabric.Object instance
  // ... do some stuff ...
});
Parameters:
Name Type Attributes Description
json String | Object JSON string or object
callback function Callback, invoked when json is parsed and corresponding objects (e.g: fabric.Image) are initialized
reviver function <optional>
Method for further parsing of JSON elements, called after each fabric object created.
Returns:
instance
Type
fabric.Canvas

moveTo(object, index) → {fabric.Canvas}

Source:
Inherited From:
Moves an object to specified level in stack of drawn objects
Parameters:
Name Type Description
object fabric.Object Object to send
index Number Position to move to
Returns:
thisArg
Type
fabric.Canvas

relativePan(point) → {fabric.Canvas}

Source:
Inherited From:
Pans viewpoint relatively
Parameters:
Name Type Description
point fabric.Point (position vector) to move by
Returns:
instance
Type
fabric.Canvas

remove(…object) → {Self}

Source:
Inherited From:
Mixes In:
Removes objects from a collection, then renders canvas (if `renderOnAddRemove` is not `false`)
Parameters:
Name Type Attributes Description
object fabric.Object <repeatable>
Zero or more fabric instances
Returns:
thisArg
Type
Self

removeListeners()

Source:
Removes all event listeners

renderAll() → {fabric.Canvas}

Source:
Overrides:
Renders both the top canvas and the secondary container canvas.
Returns:
instance
Type
fabric.Canvas

renderCanvas(ctx, objects) → {fabric.Canvas}

Source:
Inherited From:
Renders background, objects, overlay and controls.
Parameters:
Name Type Description
ctx CanvasRenderingContext2D
objects Array to render
Returns:
instance
Type
fabric.Canvas

renderTop() → {fabric.Canvas}

Source:
Method to render only the top canvas. Also used to render the group selection box.
Returns:
thisArg
Type
fabric.Canvas

requestRenderAll() → {fabric.Canvas}

Source:
Inherited From:
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.
Returns:
instance
Type
fabric.Canvas

restorePointerVpt(pointer) → {Object}

Source:
Returns pointer coordinates without the effect of the viewport
Parameters:
Name Type Description
pointer Object with "x" and "y" number values
Returns:
object with "x" and "y" number values
Type
Object

sendBackwards(object, intersectingopt) → {fabric.Canvas}

Source:
Inherited From:
Moves an object or a selection down in stack of drawn objects An optional parameter, intersecting allows 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.
Parameters:
Name Type Attributes Description
object fabric.Object Object to send
intersecting Boolean <optional>
If `true`, send object behind next lower intersecting object
Returns:
thisArg
Type
fabric.Canvas

sendToBack(object) → {fabric.Canvas}

Source:
Inherited From:
Moves an object or the objects of a multiple selection to the bottom of the stack of drawn objects
Parameters:
Name Type Description
object fabric.Object Object to send to back
Returns:
thisArg
Type
fabric.Canvas

setActiveObject(object, eopt) → {fabric.Canvas}

Source:
Sets given object as the only active object on canvas
Parameters:
Name Type Attributes Description
object fabric.Object Object to set as an active one
e Event <optional>
Event (passed along when firing "object:selected")
Returns:
thisArg
Type
fabric.Canvas

setBackgroundColor(backgroundColor, callback) → {fabric.Canvas}

Source:
Inherited From:
See:
Sets background color for this canvas
Examples

Normal backgroundColor - color value

canvas.setBackgroundColor('rgba(255, 73, 64, 0.6)', canvas.renderAll.bind(canvas));

fabric.Pattern used as backgroundColor

canvas.setBackgroundColor({
  source: 'http://fabricjs.com/assets/escheresque_ste.png'
}, canvas.renderAll.bind(canvas));

fabric.Pattern used as backgroundColor with repeat and offset

canvas.setBackgroundColor({
  source: 'http://fabricjs.com/assets/escheresque_ste.png',
  repeat: 'repeat',
  offsetX: 200,
  offsetY: 100
}, canvas.renderAll.bind(canvas));
Parameters:
Name Type Description
backgroundColor String | fabric.Pattern Color or pattern to set background color to
callback function Callback to invoke when background color is set
Returns:
thisArg
Type
fabric.Canvas

setBackgroundImage(image, callback, optionsopt) → {fabric.Canvas}

Source:
Inherited From:
See:
Sets background image for this canvas
Examples

Normal backgroundImage with left/top = 0

canvas.setBackgroundImage('http://fabricjs.com/assets/honey_im_subtle.png', canvas.renderAll.bind(canvas), {
  // Needed to position backgroundImage at 0/0
  originX: 'left',
  originY: 'top'
});

backgroundImage with different properties

canvas.setBackgroundImage('http://fabricjs.com/assets/honey_im_subtle.png', canvas.renderAll.bind(canvas), {
  opacity: 0.5,
  angle: 45,
  left: 400,
  top: 400,
  originX: 'left',
  originY: 'top'
});

Stretched backgroundImage #1 - width/height correspond to canvas width/height

fabric.Image.fromURL('http://fabricjs.com/assets/honey_im_subtle.png', function(img, isError) {
   img.set({width: canvas.width, height: canvas.height, originX: 'left', originY: 'top'});
   canvas.setBackgroundImage(img, canvas.renderAll.bind(canvas));
});

Stretched backgroundImage #2 - width/height correspond to canvas width/height

canvas.setBackgroundImage('http://fabricjs.com/assets/honey_im_subtle.png', canvas.renderAll.bind(canvas), {
  width: canvas.width,
  height: canvas.height,
  // Needed to position backgroundImage at 0/0
  originX: 'left',
  originY: 'top'
});

backgroundImage loaded from cross-origin

canvas.setBackgroundImage('http://fabricjs.com/assets/honey_im_subtle.png', canvas.renderAll.bind(canvas), {
  opacity: 0.5,
  angle: 45,
  left: 400,
  top: 400,
  originX: 'left',
  originY: 'top',
  crossOrigin: 'anonymous'
});
Parameters:
Name Type Attributes Description
image fabric.Image | String fabric.Image instance or URL of an image to set background to
callback function Callback to invoke when image is loaded and set as background
options Object <optional>
Optional options to set for the background image.
Returns:
thisArg
Type
fabric.Canvas

setCursor(value)

Source:
See:
Set the cursor type of the canvas element
Parameters:
Name Type Description
value String Cursor type of the canvas element.

setDimensions(dimensions, optionsopt) → {fabric.Canvas}

Source:
Inherited From:
Sets dimensions (width, height) of this canvas instance. when options.cssOnly flag active you should also supply the unit of measure (px/%/em)
Parameters:
Name Type Attributes Description
dimensions Object Object with width/height properties
Properties
Name Type Attributes Description
width Number | String <optional>
Width of canvas element
height Number | String <optional>
Height of canvas element
options Object <optional>
Options object
Properties
Name Type Attributes Default Description
backstoreOnly Boolean <optional>
false Set the given dimensions only as canvas backstore dimensions
cssOnly Boolean <optional>
false Set the given dimensions only as css dimensions
Returns:
thisArg
Type
fabric.Canvas

setHeight(value, optionsopt) → {fabric.Canvas}

Source:
Inherited From:
Sets height of this canvas instance
Parameters:
Name Type Attributes Description
value Number | String Value to set height to
options Object <optional>
Options object
Properties
Name Type Attributes Default Description
backstoreOnly Boolean <optional>
false Set the given dimensions only as canvas backstore dimensions
cssOnly Boolean <optional>
false Set the given dimensions only as css dimensions
Returns:
instance
Type
fabric.Canvas

setOverlayColor(overlayColor, callback) → {fabric.Canvas}

Source:
Inherited From:
See:
Sets foreground color for this canvas
Examples

Normal overlayColor - color value

canvas.setOverlayColor('rgba(255, 73, 64, 0.6)', canvas.renderAll.bind(canvas));

fabric.Pattern used as overlayColor

canvas.setOverlayColor({
  source: 'http://fabricjs.com/assets/escheresque_ste.png'
}, canvas.renderAll.bind(canvas));

fabric.Pattern used as overlayColor with repeat and offset

canvas.setOverlayColor({
  source: 'http://fabricjs.com/assets/escheresque_ste.png',
  repeat: 'repeat',
  offsetX: 200,
  offsetY: 100
}, canvas.renderAll.bind(canvas));
Parameters:
Name Type Description
overlayColor String | fabric.Pattern Color or pattern to set foreground color to
callback function Callback to invoke when foreground color is set
Returns:
thisArg
Type
fabric.Canvas

setOverlayImage(image, callback, optionsopt) → {fabric.Canvas}

Source:
Inherited From:
See:
Sets overlay image for this canvas
Examples

Normal overlayImage with left/top = 0

canvas.setOverlayImage('http://fabricjs.com/assets/jail_cell_bars.png', canvas.renderAll.bind(canvas), {
  // Needed to position overlayImage at 0/0
  originX: 'left',
  originY: 'top'
});

overlayImage with different properties

canvas.setOverlayImage('http://fabricjs.com/assets/jail_cell_bars.png', canvas.renderAll.bind(canvas), {
  opacity: 0.5,
  angle: 45,
  left: 400,
  top: 400,
  originX: 'left',
  originY: 'top'
});

Stretched overlayImage #1 - width/height correspond to canvas width/height

fabric.Image.fromURL('http://fabricjs.com/assets/jail_cell_bars.png', function(img, isError) {
   img.set({width: canvas.width, height: canvas.height, originX: 'left', originY: 'top'});
   canvas.setOverlayImage(img, canvas.renderAll.bind(canvas));
});

Stretched overlayImage #2 - width/height correspond to canvas width/height

canvas.setOverlayImage('http://fabricjs.com/assets/jail_cell_bars.png', canvas.renderAll.bind(canvas), {
  width: canvas.width,
  height: canvas.height,
  // Needed to position overlayImage at 0/0
  originX: 'left',
  originY: 'top'
});

overlayImage loaded from cross-origin

canvas.setOverlayImage('http://fabricjs.com/assets/jail_cell_bars.png', canvas.renderAll.bind(canvas), {
  opacity: 0.5,
  angle: 45,
  left: 400,
  top: 400,
  originX: 'left',
  originY: 'top',
  crossOrigin: 'anonymous'
});
Parameters:
Name Type Attributes Description
image fabric.Image | String fabric.Image instance or URL of an image to set overlay to
callback function callback to invoke when image is loaded and set as an overlay
options Object <optional>
Optional options to set for the overlay image.
Returns:
thisArg
Type
fabric.Canvas

setViewportTransform(vpt) → {fabric.Canvas}

Source:
Overrides:
Sets viewport transform of this canvas instance
Parameters:
Name Type Description
vpt Array the transform in the form of context.transform
Returns:
instance
Type
fabric.Canvas

setWidth(value, optionsopt) → {fabric.Canvas}

Source:
Inherited From:
Sets width of this canvas instance
Parameters:
Name Type Attributes Description
value Number | String Value to set width to
options Object <optional>
Options object
Properties
Name Type Attributes Default Description
backstoreOnly Boolean <optional>
false Set the given dimensions only as canvas backstore dimensions
cssOnly Boolean <optional>
false Set the given dimensions only as css dimensions
Returns:
instance
Type
fabric.Canvas

setZoom(value) → {fabric.Canvas}

Source:
Inherited From:
Sets zoom level of this canvas instance
Parameters:
Name Type Description
value Number to set zoom to, less than 1 zooms out
Returns:
instance
Type
fabric.Canvas

size() → {Number}

Source:
Inherited From:
Mixes In:
Returns a size of a collection (i.e: length of an array containing its objects)
Returns:
Collection size
Type
Number

straightenObject(object) → {fabric.Canvas}

Source:
Inherited From:
Straightens object, then rerenders canvas
Parameters:
Name Type Description
object fabric.Object Object to straighten
Returns:
thisArg
Type
fabric.Canvas

toCanvasElement(multiplieropt, croppingopt)

Source:
Inherited From:
Create a new HTMLCanvas element painted with the current canvas content. No need to resize the actual one or repaint it. Will transfer object ownership to a new canvas, paint it, and set everything back. This is an intermediary step used to get to a dataUrl but also it is useful to create quick image copies of a canvas without passing for the dataUrl string
Parameters:
Name Type Attributes Description
multiplier Number <optional>
a zoom factor.
cropping Object <optional>
Cropping informations
Properties
Name Type Attributes Description
left Number <optional>
Cropping left offset.
top Number <optional>
Cropping top offset.
width Number <optional>
Cropping width.
height Number <optional>
Cropping height.

toDatalessJSON(propertiesToIncludeopt) → {String}

Source:
Inherited From:
Returns dataless JSON representation of canvas
Parameters:
Name Type Attributes Description
propertiesToInclude Array <optional>
Any properties that you might want to additionally include in the output
Returns:
json string
Type
String

toDatalessObject(propertiesToIncludeopt) → {Object}

Source:
Inherited From:
Returns dataless object representation of canvas
Parameters:
Name Type Attributes Description
propertiesToInclude Array <optional>
Any properties that you might want to additionally include in the output
Returns:
object representation of an instance
Type
Object

toDataURL(optionsopt) → {String}

Source:
Inherited From:
See:
Exports canvas element to a dataurl image. Note that when multiplier is used, cropping is scaled appropriately
Examples

Generate jpeg dataURL with lower quality

var dataURL = canvas.toDataURL({
  format: 'jpeg',
  quality: 0.8
});

Generate cropped png dataURL (clipping of canvas)

var dataURL = canvas.toDataURL({
  format: 'png',
  left: 100,
  top: 100,
  width: 200,
  height: 200
});

Generate double scaled png dataURL

var dataURL = canvas.toDataURL({
  format: 'png',
  multiplier: 2
});
Parameters:
Name Type Attributes Description
options Object <optional>
Options object
Properties
Name Type Attributes Default Description
format String <optional>
png The format of the output image. Either "jpeg" or "png"
quality Number <optional>
1 Quality level (0..1). Only used for jpeg.
multiplier Number <optional>
1 Multiplier to scale by, to have consistent
left Number <optional>
Cropping left offset. Introduced in v1.2.14
top Number <optional>
Cropping top offset. Introduced in v1.2.14
width Number <optional>
Cropping width. Introduced in v1.2.14
height Number <optional>
Cropping height. Introduced in v1.2.14
enableRetinaScaling Boolean <optional>
Enable retina scaling for clone image. Introduce in 2.0.0
Returns:
Returns a data: URL containing a representation of the object in the format specified by options.format
Type
String

toJSON(propertiesToIncludeopt) → {Object}

Source:
Inherited From:
Tutorials:
See:
Returns Object representation of canvas this alias is provided because if you call JSON.stringify on an instance, the toJSON object will be invoked if it exists. Having a toJSON method means you can do JSON.stringify(myCanvas)
Examples

JSON without additional properties

var json = canvas.toJSON();

JSON with additional properties included

var json = canvas.toJSON(['lockMovementX', 'lockMovementY', 'lockRotation', 'lockScalingX', 'lockScalingY']);

JSON without default values

canvas.includeDefaultValues = false;
var json = canvas.toJSON();
Parameters:
Name Type Attributes Description
propertiesToInclude Array <optional>
Any properties that you might want to additionally include in the output
Returns:
JSON compatible object
Type
Object

toObject(propertiesToIncludeopt) → {Object}

Source:
Inherited From:
Returns object representation of canvas
Parameters:
Name Type Attributes Description
propertiesToInclude Array <optional>
Any properties that you might want to additionally include in the output
Returns:
object representation of an instance
Type
Object

toString() → {String}

Source:
Inherited From:
Returns a string representation of an instance
Returns:
string representation of an instance
Type
String

toSVG(optionsopt, reviveropt) → {String}

Source:
Inherited From:
Tutorials:
See:
Returns SVG representation of canvas
Examples

Normal SVG output

var svg = canvas.toSVG();

SVG output without preamble (without <?xml ../>)

var svg = canvas.toSVG({suppressPreamble: true});

SVG output with viewBox attribute

var svg = canvas.toSVG({
  viewBox: {
    x: 100,
    y: 100,
    width: 200,
    height: 300
  }
});

SVG output with different encoding (default: UTF-8)

var svg = canvas.toSVG({encoding: 'ISO-8859-1'});

Modify SVG output with reviver function

var svg = canvas.toSVG(null, function(svg) {
  return svg.replace('stroke-dasharray: ; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; ', '');
});
Parameters:
Name Type Attributes Description
options Object <optional>
Options object for SVG output
Properties
Name Type Attributes Default Description
suppressPreamble Boolean <optional>
false If true xml tag is not included
viewBox Object <optional>
SVG viewbox object
Properties
Name Type Attributes Description
x Number <optional>
x-coordinate of viewbox
y Number <optional>
y-coordinate of viewbox
width Number <optional>
Width of viewbox
height Number <optional>
Height of viewbox
encoding String <optional>
UTF-8 Encoding of SVG output
width String <optional>
desired width of svg with or without units
height String <optional>
desired height of svg with or without units
reviver function <optional>
Method for further parsing of svg elements, called after each fabric object converted into svg representation.
Returns:
SVG string
Type
String

viewportCenterObject(object) → {fabric.Canvas}

Source:
Inherited From:
Centers object vertically and horizontally in the viewport
Parameters:
Name Type Description
object fabric.Object Object to center vertically and horizontally
Returns:
thisArg
Type
fabric.Canvas

viewportCenterObjectH(object) → {fabric.Canvas}

Source:
Inherited From:
Centers object horizontally in the viewport, object.top is unchanged
Parameters:
Name Type Description
object fabric.Object Object to center vertically and horizontally
Returns:
thisArg
Type
fabric.Canvas

viewportCenterObjectV(object) → {fabric.Canvas}

Source:
Inherited From:
Centers object Vertically in the viewport, object.top is unchanged
Parameters:
Name Type Description
object fabric.Object Object to center vertically and horizontally
Returns:
thisArg
Type
fabric.Canvas

zoomToPoint(point, value) → {fabric.Canvas}

Source:
Inherited From:
Sets zoom level of this canvas instance, the zoom centered around point meaning that following zoom to point with the same point will have the visual effect of the zoom originating from that point. The point won't move. It has nothing to do with canvas center or visual center of the viewport.
Parameters:
Name Type Description
point fabric.Point to zoom with respect to
value Number to set zoom to, less than 1 zooms out
Returns:
instance
Type
fabric.Canvas