Class: Canvas

fabric.Canvas

new Canvas()

Canvas class
Source:
Tutorials:
See:
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
  • drop:before before drop event. same native event.event: This is added to handle edge cases
  • 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,event: receives the context in the callback

Extends

Members

allowTouchScrolling :Boolean

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

altActionKey :String

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
Since:
  • 1.6.2
Default Value:
  • shiftKey
Source:

altSelectionKey :null|String

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
Since:
  • 1.6.5
Source:

backgroundColor :String|fabric.Pattern

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

backgroundImage :fabric.Image

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

backgroundVpt :Boolean

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

centeredKey :String

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
Since:
  • 1.6.2
Default Value:
  • altKey
Source:

centeredRotation :Boolean

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

centeredScaling :Boolean

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

clipPath :fabric.Object

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

containerClass :String

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

controlsAboveOverlay :Boolean

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

defaultCursor :String

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

enablePointerEvents :Boolean

When the option is enabled, PointerEvent is used instead of MouseEvent.
Type:
  • Boolean
Source:

enableRetinaScaling :Boolean

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

fireMiddleClick :Boolean

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

fireRightClick :Boolean

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

freeDrawingCursor :String

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

FX_DURATION :Number

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

hoverCursor :String

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

imageSmoothingEnabled :Boolean

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

includeDefaultValues :Boolean

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

interactive :Boolean

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

isDrawingMode :Boolean

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

moveCursor :String

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

notAllowedCursor :String

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

overlayColor :String|fabric.Pattern

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

overlayImage :fabric.Image

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

overlayVpt :Boolean

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

perPixelTargetFind :Boolean

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

preserveObjectStacking :Boolean

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

renderOnAddRemove :Boolean

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

selection :Boolean

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

selectionBorderColor :String

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

selectionColor :String

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

selectionDashArray :Array

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

selectionFullyContained :Boolean

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

selectionKey :String|Array

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
Since:
  • 1.6.2
Default Value:
  • shiftKey
Source:

selectionLineWidth :Number

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

skipOffscreen :Boolean

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

skipTargetFind :Boolean

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

snapAngle :Number

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

snapThreshold :null|Number

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
Since:
  • 1.6.7
Source:

stateful :Boolean

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

stopContextMenu :Boolean

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

svgViewportTransformation :Boolean

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

targetFindTolerance :Number

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

targets :Array.<fabric.Object>

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

uniformScaling :Boolean

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

uniScaleKey :String

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
Since:
  • 1.6.2
Default Value:
  • shiftKey
Source:

viewportTransform :Array

The transformation (a Canvas 2D API transform matrix) which focuses the viewport
Type:
  • Array
Inherited From:
Source:
Examples

Default transform

canvas.viewportTransform = [1, 0, 0, 1, 0, 0];

Scale by 70% and translate toward bottom-right by 50, without skewing

canvas.viewportTransform = [0.7, 0, 0, 0.7, 50, 50];

vptCoords

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

Methods

__onMouseWheel(e)

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

_chooseObjectsToRender() → {Array}

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

_onDrop(e)

`drop:before` is a an event that allow you to schedule logic before the `drop` event. Prefer `drop` event always, but if you need to run some drop-disabling logic on an event, since there is no way to handle event handlers ordering, use `drop:before`
Parameters:
Name Type Description
e Event
Source:

_setCursorFromEvent(e, target)

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

absolutePan(point) → {fabric.Canvas}

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

add(…object) → {Self}

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
Inherited From:
Mixes In:
Source:
Returns:
thisArg
Type
Self

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

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

bringToFront(object) → {fabric.Canvas}

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

calcOffset() → {fabric.Canvas}

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

calcViewportBoundaries() → {Object}

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

centerObject(object) → {fabric.Canvas}

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

centerObjectH(object) → {fabric.Canvas}

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

centerObjectV(object) → {fabric.Canvas}

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

clear() → {fabric.Canvas}

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

clearContext(ctx) → {fabric.Canvas}

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

clone(callbackopt, propertiesopt)

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

cloneWithoutData(callbackopt)

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

complexity() → {Number}

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

contains(object, deepopt) → {Boolean}

Returns true if collection contains an object
Parameters:
Name Type Attributes Default Description
object Object Object to check against
deep Boolean <optional>
false `true` to check all descendants, `false` to check only `_objects`
Inherited From:
Mixes In:
Source:
Returns:
`true` if collection contains an object
Type
Boolean

createSVGFontFacesMarkup(objects) → {String}

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

createSVGRefElementsMarkup() → {String}

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

discardActiveObject(e) → {fabric.Canvas}

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
Source:
Returns:
thisArg
Type
fabric.Canvas

dispose() → {fabric.Canvas}

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

drawClipPathOnCanvas(ctx)

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

drawControls(ctx)

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

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

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
Source:
Returns:
the target found
Type
fabric.Object

fire(eventName, optionsopt) → {Self}

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

forEachObject(callback, context) → {Self}

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)
Inherited From:
Mixes In:
Source:
Returns:
thisArg
Type
Self

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

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

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

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

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

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

fxStraightenObject(object) → {fabric.Canvas}

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

getActiveObject() → {fabric.Object}

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

getActiveObjects() → {fabric.Object}

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

getCenter() → {Object}

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

getContext() → {CanvasRenderingContext2D}

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

getElement() → {HTMLCanvasElement}

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

getHeight() → {Number}

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

getObjects(typeopt) → {Array}

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
Inherited From:
Mixes In:
Source:
Returns:
Type
Array

getPointer(e, ignoreZoom) → {Object}

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
Source:
Returns:
object with "x" and "y" number values
Type
Object

getSelectionContext() → {CanvasRenderingContext2D}

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

getSelectionElement() → {HTMLCanvasElement}

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

getVpCenter() → {fabric.Point}

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

getWidth() → {Number}

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

getZoom() → {Number}

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

initialize(el, optionsopt) → {Object}

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

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

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
Inherited From:
Mixes In:
Source:
Returns:
thisArg
Type
Self

isEmpty() → {Boolean}

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

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

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

item(index) → {Self}

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

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

Populates canvas with data from the specified JSON. JSON format must conform to the one of fabric.Canvas#toJSON
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.
Inherited From:
Source:
Tutorials:
See:
Returns:
instance
Type
fabric.Canvas
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 ...
});

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

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

relativePan(point) → {fabric.Canvas}

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

remove(…object) → {Self}

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
Inherited From:
Mixes In:
Source:
Returns:
thisArg
Type
Self

removeListeners()

Removes all event listeners
Source:

renderAll() → {fabric.Canvas}

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

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

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

renderTop() → {fabric.Canvas}

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

requestRenderAll() → {fabric.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.
Inherited From:
Source:
Returns:
instance
Type
fabric.Canvas

restorePointerVpt(pointer) → {Object}

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

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

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

sendToBack(object) → {fabric.Canvas}

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

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

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")
Source:
Returns:
thisArg
Type
fabric.Canvas

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

Sets background color for this 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
Inherited From:
Source:
See:
Returns:
thisArg
Type
fabric.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));

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

Sets background image for this canvas
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.
Inherited From:
Source:
See:
Returns:
thisArg
Type
fabric.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'
});

setCursor(value)

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

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

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

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

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

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

Sets foreground color for this 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
Inherited From:
Source:
See:
Returns:
thisArg
Type
fabric.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));

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

Sets overlay image for this canvas
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.
Inherited From:
Source:
See:
Returns:
thisArg
Type
fabric.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'
});

setViewportTransform(vpt) → {fabric.Canvas}

Sets viewport transformation of this canvas instance
Parameters:
Name Type Description
vpt Array a Canvas 2D API transform matrix
Overrides:
Source:
Returns:
instance
Type
fabric.Canvas

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

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

setZoom(value) → {fabric.Canvas}

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

size() → {Number}

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

straightenObject(object) → {fabric.Canvas}

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

toCanvasElement(multiplieropt, croppingopt)

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

toDatalessJSON(propertiesToIncludeopt) → {String}

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
Inherited From:
Source:
Returns:
json string
Type
String

toDatalessObject(propertiesToIncludeopt) → {Object}

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
Inherited From:
Source:
Returns:
object representation of an instance
Type
Object

toDataURL(optionsopt) → {String}

Exports canvas element to a dataurl image. Note that when multiplier is used, cropping is scaled appropriately
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
Inherited From:
Source:
See:
Returns:
Returns a data: URL containing a representation of the object in the format specified by options.format
Type
String
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
});

toJSON(propertiesToIncludeopt) → {Object}

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)
Parameters:
Name Type Attributes Description
propertiesToInclude Array <optional>
Any properties that you might want to additionally include in the output
Inherited From:
Source:
Tutorials:
See:
Returns:
JSON compatible object
Type
Object
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();

toObject(propertiesToIncludeopt) → {Object}

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
Inherited From:
Source:
Returns:
object representation of an instance
Type
Object

toString() → {String}

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

toSVG(optionsopt, reviveropt) → {String}

Returns SVG representation of canvas
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.
Inherited From:
Source:
Tutorials:
See:
Returns:
SVG string
Type
String
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; ', '');
});

viewportCenterObject(object) → {fabric.Canvas}

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

viewportCenterObjectH(object) → {fabric.Canvas}

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

viewportCenterObjectV(object) → {fabric.Canvas}

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

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

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