Class Canvas

Hierarchy

  • SelectableCanvas
    • Canvas

Implements

Constructors

Properties

Accessors

Methods

__onMouseDown __onMouseMove __onMouseUp __onMouseWheel __serializeBgOverlay _basicEventHandler _beforeTransform _cacheTransformEventData _centerObject _checkTarget _chooseObjectsToRender _createCacheCanvas _discardActiveObject _drawSelection _finalizeCurrentTransform _fireEnterLeaveEvents _fireOverOutEvents _fireSelectionEvents _getEventPrefix _getOriginFromCorner _handleEvent _isMainEvent _isRetinaScaling _isSelectionKeyPressed _onContextMenu _onDoubleClick _onDragEnd _onDragEnter _onDragLeave _onDragOver _onDragProgress _onDragStart _onDrop _onMouseDown _onMouseDownInDrawingMode _onMouseEnter _onMouseMove _onMouseMoveInDrawingMode _onMouseOut _onMouseUp _onMouseUpInDrawingMode _onMouseWheel _onObjectAdded _onObjectRemoved _onResize _onStackOrderChanged _onTouchEnd _onTouchStart _performTransformAction _realizeGroupTransformOnObject _renderBackground _renderBackgroundOrOverlay _renderDragEffects _renderObjects _renderOverlay _resetTransformEventData _searchPossibleTargets _set _setActiveObject _setCursorFromEvent _setDimensionsImpl _setObject _setOptions _setSVGBgOverlayColor _setSVGBgOverlayImage _setSVGHeader _setSVGObject _setSVGObjects _setSVGPreamble _setupCurrentTransform _shouldClearSelection _shouldRender _toObject _toObjectMethod _transformObject absolutePan add addOrRemove bringObjectForward bringObjectToFront calcOffset calcViewportBoundaries cancelRequestedRender centerObject centerObjectH centerObjectV clear clearContext clone cloneWithoutData collectObjects complexity contains createSVGClipPathMarkup createSVGFontFacesMarkup createSVGRefElementsMarkup destroy discardActiveObject dispose drawClipPathOnCanvas drawControls endCurrentTransform findDragTargets findNewLowerIndex findNewUpperIndex findTarget fire fireSyntheticInOutEvents forEachObject get getActiveObject getActiveObjects getActiveSelection getCenter getCenterPoint getContext getElement getHeight getObjects getPointer getPointerId getRetinaScaling getSelectionContext getSelectionElement getTopContext getVpCenter getWidth getZoom handleMultiSelection handleSelection initElements insertAt isEmpty isTargetTransparent item loadFromJSON moveObjectTo off on once relativePan remove removeListeners renderAll renderAndReset renderCanvas renderTop renderTopLayer requestRenderAll restorePointerVpt searchPossibleTargets sendObjectBackwards sendObjectToBack set setActiveObject setCursor setDimensions setHeight setTargetFindTolerance setViewportTransform setWidth setZoom size toCanvasElement toDataURL toDatalessJSON toDatalessObject toJSON toObject toSVG toString toggle viewportCenterObject viewportCenterObjectH viewportCenterObjectV zoomToPoint getDefaults

Constructors

  • Parameters

    • Optional el: string | HTMLCanvasElement
    • options: TCanvasOptions = {}

    Returns Canvas

Properties

__cleanupTask?: {
    kill: ((reason?) => void);
    (): void;
}

Type declaration

    • (): void
    • Returns void

  • kill: ((reason?) => void)
      • (reason?): void
      • Parameters

        • Optional reason: any

        Returns void

_absolutePointer?: Point

During a mouse event we may need the pointer multiple times in multiple functions. _absolutePointer holds a reference to the pointer in fabricCanvas/design coordinates that is valid for the event lifespan. Every fabricJS mouse event create and delete the cache every time We do this because there are some HTML DOM inspection functions to get the actual pointer coordinates

_activeSelection: ActiveSelection
_currentTransform: null | Transform = null

hold a reference to a data structure that contains information on the current on going transform

Holds a reference to an object on the canvas from where the drag operation started

Holds a reference to an object on the canvas that is receiving the drag over event.

Holds a reference to an object on the canvas that is the current drop target May differ from _draggedoverTarget

Todo

inspect whether _draggedoverTarget and _dropTarget should be merged somehow

_groupSelector: null | {
    deltaX: number;
    deltaY: number;
    x: number;
    y: number;
} = null

hold a reference to a data structure used to track the selection box on canvas drag on the current on going transform

Type declaration

  • deltaX: number
  • deltaY: number
  • x: number
  • y: number

Keep track of the hovered target

hold the list of nested targets hovered

_isClick: boolean
_isCurrentlyDrawing: boolean

hold the list of objects to render

_offset: {
    left: number;
    top: number;
}

Type declaration

  • left: number
  • top: number
_pointer?: Point

During a mouse event we may need the pointer multiple times in multiple functions. _pointer holds a reference to the pointer in html coordinates that is valid for the event lifespan. Every fabricJS mouse event create and delete the cache every time We do this because there are some HTML DOM inspection functions to get the actual pointer coordinates

During a mouse event we may need the target multiple times in multiple functions. _target holds a reference to the target that is valid for the event lifespan. Every fabricJS mouse event create and delete the cache every time

_willAddMouseDown: number

Holds a reference to a setTimeout timer for event synchronization

allowTouchScrolling: boolean

Todo

move to Canvas

altActionKey: TOptionalModifierKey

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.

Since

1.6.2

Default


altSelectionKey: TOptionalModifierKey

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.

Since

1.6.5

Default


backgroundColor: string | TFiller

Background color of canvas instance.

Default


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

Default


backgroundVpt: boolean

if set to false background image is not affected by viewport transform

Since

1.6.3

Todo

we should really find a different way to do this

Default


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.

Since

1.6.2

Default


centeredRotation: boolean

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

Since

1.3.4

Default


centeredScaling: boolean

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

Since

1.3.4

Default


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

containerClass: string

Default element class that's given to wrapper (div) element of canvas

Default


Deprecated

customize CanvasDOMManager instead or access elements directly

contextTopDirty: boolean = false

internal flag used to understand if the context top requires a cleanup in case this is true, the contextTop will be cleared at the next render

controlsAboveOverlay: boolean

Todo

move to Canvas

defaultCursor: string

Default cursor value used for the entire canvas

Default

default
destroyed?: boolean

If true the Canvas is in the process or has been disposed/destroyed. No more rendering operation will be executed on this canvas.

disposed?: boolean

Started the process of disposing but not done yet. WIll likely complete the render cycle already scheduled but stopping adding more.

enablePointerEvents: boolean

When the option is enabled, PointerEvent is used instead of TPointerEvent.

Default


enableRetinaScaling: boolean

When true, canvas is scaled by devicePixelRatio for better rendering on retina screens

Default


fireMiddleClick: boolean

Indicates if the canvas can fire middle click events

Since

1.7.8

Default


fireRightClick: boolean

Indicates if the canvas can fire right click events

Since

1.6.5

Default


freeDrawingBrush?: BaseBrush
freeDrawingCursor: string

Cursor value used during free drawing

Default

crosshair
hasLostContext: boolean
height: number

Height in virtual/logical pixels of the canvas. The canvas can be taller than width if retina scaling is active

hoverCursor: string

Default cursor value used when hovering over an object on canvas

Default

move
imageSmoothingEnabled: boolean

Indicates whether this canvas will use image smoothing, this is on by default in browsers

Default


includeDefaultValues: boolean

Indicates whether toObject/toDatalessObject should include default values if set to false, takes precedence over the object value.

Default


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.

mainTouchId: null | number

Contains the id of the touch event that owns the fabric transform

moveCursor: string

Default cursor value used when moving an object on canvas

Default

move
nextRenderHandle: number
notAllowedCursor: string

Cursor value used for disabled elements ( corners with disabled action )

Since

2.0.0

Default

not-allowed
overlayColor: string | TFiller

Overlay color of canvas instance.

Since

1.3.9

Default


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

Default


overlayVpt: boolean

if set to false overlay image is not affected by viewport transform

Since

1.6.3

Todo

we should really find a different way to do this

Default


perPixelTargetFind: boolean

When true, object detection happens on per-pixel basis rather than on per-bounding-box

Default


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

Default


renderOnAddRemove: boolean

Indicates whether StaticCanvas#add, StaticCanvas#insertAt and StaticCanvas#remove, StaticCanvas#moveTo, 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 queued 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.

Default


selection: boolean

Indicates whether group selection should be enabled

Default


selectionBorderColor: string

Color of the border of selection (usually slightly darker than color of selection itself)

Default


selectionColor: string

Color of selection

Default


selectionDashArray: number[]

Default dash array pattern If not empty the selection border is dashed

selectionFullyContained: boolean

Select only shapes that are fully contained in the dragged selection rectangle.

Default


selectionKey: TOptionalModifierKey | ("altKey" | "shiftKey" | "ctrlKey" | "metaKey")[]

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.

Since

1.6.2

Default


selectionLineWidth: number

Width of a line used in object/group selection

Default


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.

Default

true
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.

Default


stopContextMenu: boolean

Indicates if the right click on canvas can output the context menu or not

Since

1.6.5

Default


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.

Default


targetFindTolerance: number

Number of pixels around target pixel to tolerate (consider active) during object detection

Default


Keep track of the subTargets for Mouse Events

textEditingManager: TextEditingManager = ...

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.

Since

1.6.2

Default


uniformScaling: boolean

When true, objects can be transformed by one side (unproportionately) when dragged on the corners that normally would not do that.

Default


Since

fabric 4.0 // changed name and default value

viewportTransform: TMat2D

The transformation (a Canvas 2D API transform matrix) which focuses the viewport

Example

Default transform

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

Example

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

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

Default


vptCoords: TCornerPoint

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.

width: number

Width in virtual/logical pixels of the canvas. The canvas can be larger than width if retina scaling is active

ownDefaults: Record<string, any> = canvasDefaults

Accessors

  • get contextContainer(): CanvasRenderingContext2D
  • Returns CanvasRenderingContext2D

  • get lowerCanvasEl(): HTMLCanvasElement
  • A reference to the canvas actual HTMLCanvasElement. Can be use to read the raw pixels, but never write or manipulate

    Returns HTMLCanvasElement

Methods

  • Private

    Method that defines the actions when mouse is clicked on canvas. The method inits the currentTransform parameters and renders all the canvas so the current image can be placed on the top canvas and the rest in on the container one.

    Parameters

    Returns void

  • Private

    Method that defines the actions when mouse is hovering the canvas. The currentTransform parameter will define whether the user is rotating/scaling/translating an image or neither of them (only hovering). A group selection is also possible and would cancel all any other type of action. In case of an image transformation only the top canvas will be rendered.

    Parameters

    Returns void

  • Private

    Method that defines the actions when mouse is released on canvas. The method resets the currentTransform parameters, store the image corner position in the image object and render the canvas on top.

    Parameters

    Returns void

  • Private

    Parameters

    Returns any

  • Private

    Cache common information needed during event processing

    Parameters

    Returns void

  • This is supposed to be equivalent to discardActiveObject but without firing any selection events ( can still fire object transformation events ). There is commitment to have this stay this way. This is the functional part of discardActiveObject.

    Parameters

    Returns this is {
        _activeObject: undefined;
    }

    true if the active object has been discarded

  • Private

    Parameters

    • ctx: CanvasRenderingContext2D

      to draw the selection on

    Returns void

  • Private

    Parameters

    • e: TPointerEvent

      send the mouse event that generate the finalize down, so it can be used in the event

    Returns void

  • Private

    return an event prefix pointer or mouse.

    Returns "mouse" | "pointer"

  • Private

    Handle event firing for target and subtargets

    Parameters

    • e: TPointerEvent

      event from mouse

    • eventType: TPointerEventNames

      event to fire (up, down or move)

    • Optional button: number = LEFT_CLICK

      button used in the event 1 = left, 2 = middle, 3 = right

    • isClick: boolean = false

      for left button only, indicates that the mouse up happened without move.

    Returns void

  • Private

    Determines if an event has the id of the event that is considered main

    Parameters

    Returns boolean

  • Private

    takes an event and determines if selection key has been pressed

    Parameters

    Returns boolean

  • Private

    fire dragleave on dragover targets

    Parameters

    • Optional e: DragEvent

      Event object fired on Event.js shake

    Returns void

  • Private

    fire dragleave on dragover targets

    Parameters

    • Optional e: DragEvent

      Event object fired on Event.js shake

    Returns void

  • Private

    fire drag event on canvas and drag source

    Parameters

    • e: DragEvent

    Returns void

  • Private

    supports native like text dragging

    Parameters

    • e: DragEvent

    Returns void

  • Private

    drop:before is a an event that allows 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

    • e: DragEvent

    Returns void

  • Private

    Parameters

    • Optional e: MouseEvent

      Event object fired on wheel event

    Returns void

  • Private

    Parameters

    • e: TouchEvent

      Event object fired on mousedown

    Returns void

  • Private

    Parameters

    • e: TouchEvent

      Event object fired on mousedown

    Returns void

  • Private

    Parameters

    • ctx: CanvasRenderingContext2D

      Context to render on

    Returns void

  • Private

    Parameters

    • ctx: CanvasRenderingContext2D

      Context to render on

    • property: "overlay" | "background"

      'background' or 'overlay'

    Returns void

  • Private

    Parameters

    • ctx: CanvasRenderingContext2D

      Context to render on

    Returns void

  • Private

    reset cache form common information needed during event processing

    Returns void

  • Parameters

    • key: string
    • value: any

    Returns void

  • This is supposed to be equivalent to setActiveObject but without firing any event. There is commitment to have this stay this way. This is the functional part of setActiveObject.

    Parameters

    Returns boolean

    true if the object has been selected

  • Private

    Parameters

    • obj: Record<string, any>

    Returns void

  • Protected

    Sets object's properties from options, for initialization only

    Parameters

    • Optional options: any = {}

      Options object

    Returns void

  • Private

    Parameters

    • markup: string[]
    • property: "overlay" | "background"

    Returns void

    TODO

    this seems to handle patterns but fail at gradients.

  • Private

    Parameters

    • markup: string[]
    • property: "backgroundImage" | "overlayImage"
    • reviver: TSVGReviver

    Returns void

  • Pan viewport so as to place point at top left corner of canvas

    Parameters

    • point: Point

      to move to

    Returns void

  • Parameters

    • functor: any
    • eventjsFunctor: "remove" | "add"

    Returns void

  • 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

    Returns boolean

    true if change occurred

  • Calculates canvas element offset relative to the document This method is also attached as "resize" event handler of window

    Returns {
        left: number;
        top: number;
    }

    • left: number
    • top: number
  • 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 TCornerPoint

    points.tl

    Chainable

  • Clears specified context of canvas element

    Parameters

    • ctx: CanvasRenderingContext2D

      Context to clear

    Returns void

  • Clones canvas instance

    Parameters

    • Optional properties: string[]

      Array of properties to include in the cloned canvas and children

    Returns Promise<Canvas>

  • Clones canvas instance without cloning existing data. This essentially copies canvas dimensions since loadFromJSON does not affect canvas size.

    Returns Canvas

  • Given a bounding box, return all the objects of the collection that are contained in the bounding box. If includeIntersecting is true, return also the objects that intersect the bounding box as well. This is meant to work with selection. Is not a generic method.

    Parameters

    • __namedParameters: TBBox
    • __namedParameters: {
          includeIntersecting?: boolean;
      } = {}
      • Optional includeIntersecting?: boolean

    Returns InteractiveFabricObject<Partial<FabricObjectProps>, SerializedObjectProps, ObjectEvents>[]

    array of objects contained in the bounding box, ordered from top to bottom stacking wise

  • Returns number representation of a collection complexity

    Returns number

    complexity

  • 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

    Returns string

  • Creates markup containing SVG referenced elements like patterns, gradients etc.

    Returns string

  • 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

    Returns this is {
        _activeObject: undefined;
    }

    true if the active object has been discarded

  • Waits until rendering has settled to destroy the canvas

    Returns Promise<boolean>

    a promise resolving to true once the canvas has been destroyed or to false if the canvas has was already destroyed

    Throws

    if aborted by a consequent call

  • Paint the cached clipPath on the lowerCanvasEl

    Parameters

    Returns void

  • Draws objects' controls (borders/controls)

    Parameters

    • ctx: CanvasRenderingContext2D

      Context to render controls on

    Returns void

  • End the current transform. You don't usually need to call this method unless you are interrupting a user initiated transform because of some other event ( a press of key combination, or something that block the user UX )

    Parameters

    • Optional e: TPointerEvent

      send the mouse event that generate the finalize down, so it can be used in the event

    Returns void

  • Fires event with an optional options object

    Type Parameters

    Parameters

    • eventName: K

      Event name to fire

    • Optional options: CanvasEvents[K]

      Options object

    Returns void

  • Basic getter

    Parameters

    • property: string

      Property name

    Returns any

    value of a property

  • Returns coordinates of a center of canvas. Returned value is an object with top and left properties

    Returns {
        left: number;
        top: number;
    }

    object with "top" and "left" number values

    • left: number
    • top: number

    Deprecated

    migrate to getCenterPoint

  • Returns context of canvas where objects are drawn

    Returns CanvasRenderingContext2D

  • Returns <canvas> element corresponding to this instance

    Returns HTMLCanvasElement

  • Returns pointer coordinates relative to canvas. Can return coordinates with or without viewportTransform. ignoreVpt false gives back coordinates that represent the point clicked on canvas element. ignoreVpt true gives back coordinates after being processed by the viewportTransform ( sort of coordinates of what is displayed on the canvas where you are clicking. ignoreVpt true = HTMLElement coordinates relative to top,left ignoreVpt false, default = fabric space coordinates, the same used for shape position. To interact with your shapes top and left you want to use ignoreVpt false most of the time, while ignoreVpt true will give you coordinates compatible with the object.oCoords system. of the time.

    Parameters

    Returns Point

  • Private

    Return a the id of an event. returns either the pointerId or the identifier or 0 for the mouse event

    Parameters

    • evt: TouchEvent | PointerEvent

      Event object

    Returns number

  • Private

    Returns number

    retinaScaling if applied, otherwise 1;

  • Returns context of canvas where object selection is drawn

    Returns CanvasRenderingContext2D

    Alias

  • Returns <canvas> element on which object selection is drawn

    Returns HTMLCanvasElement

  • Returns context of top canvas where interactions are drawn

    Returns CanvasRenderingContext2D

  • Calculate the point in canvas that correspond to the center of actual viewport.

    Returns Point

    vpCenter, viewport center

  • Private

    Handles multiple selection

    • toggles target selection (selects/deselects target if it isn't/is selected respectively)
    • sets the active object in case it is not set or in case there is a single active object left under active selection.

    • If the active object is the active selection we add/remove target from it
    • If not, add the active object and target to the active selection and make it the active object.

    Parameters

    Returns boolean

    true if grouping occurred

  • Parameters

    • Optional el: string | HTMLCanvasElement

    Returns void

  • Returns true if collection contains no objects

    Returns boolean

    true if collection is empty

  • Returns true if object is transparent at a certain location Clarification: this is is target transparent at location X or are controls there

    Parameters

    Returns boolean

    TODO

    this seems dumb that we treat controls with transparency. we can find controls programmatically without painting them, the cache canvas optimization is always valid

  • Populates canvas with data from the specified JSON. JSON format must conform to the one of fabric.Canvas#toJSON

    IMPORTANT: It is recommended to abort loading tasks before calling this method to prevent race conditions and unnecessary networking

    Parameters

    • json: string | Record<string, any>

      JSON string or object

    • Optional reviver: (<T>(serializedObj, instance) => void)

      Method for further parsing of JSON elements, called after each fabric object created.

    • Optional options: Abortable = {}

      options

    Returns Promise<Canvas>

    instance

    Tutorial

    http://fabricjs.com/fabric-intro-part-3#deserialization

    See

    demo

    Example

    loadFromJSON

    canvas.loadFromJSON(json).then((canvas) => canvas.requestRenderAll());
    

    Example

    loadFromJSON with reviver

    canvas.loadFromJSON(json, function(o, object) {
    // `o` = json object
    // `object` = fabric.Object instance
    // ... do some stuff ...
    }).then((canvas) => {
    ... canvas is restored, add your code.
    });
  • unsubscribe an event listener

    Type Parameters

    Parameters

    • eventName: K

      event name (eg. 'after:render')

    • handler: TEventCallback<any>

      event listener to unsubscribe

    Returns void

  • unsubscribe event listeners

    Parameters

    • handlers: EventRegistryObject<CanvasEvents>

      handlers key/value pairs (eg. {'after:render': handler, 'selection:cleared': handler})

    Returns void

  • unsubscribe all event listeners

    Returns void

  • Pans viewpoint relatively

    Parameters

    • point: Point

      (position vector) to move by

    Returns void

  • Renders both the top canvas and the secondary container canvas.

    Returns void

  • Private

    Function created to be instance bound at initialization used in requestAnimationFrame rendering Let the fabricJS call it. If you call it manually you could have more animationFrame stacking on to of each other for an imperative rendering, use canvas.renderAll

    Returns void

  • Method to render only the top canvas. Also used to render the group selection box. Does not render text selection.

    Returns void

  • text selection is rendered by the active text instance during the rendering cycle

    Parameters

    • ctx: CanvasRenderingContext2D

    Returns void

  • 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 void

  • Returns pointer coordinates without the effect of the viewport Takes a point in html canvas space and gives you back a point of the scene.

    Parameters

    • pointer: Point

      with "x" and "y" number values in canvas HTML coordinates

    Returns Point

    object with "x" and "y" number values in fabricCanvas coordinates

  • 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

    Returns boolean

    true if change occurred

  • Sets property to a given value. When changing position/dimension -related properties (left, top, scale, angle, etc.) set does not update position of object's borders/controls. If you need to update those, call setCoords().

    Parameters

    • key: string | Record<string, any>

      Property name or object (if object, iterate over the object properties)

    • Optional value: any

      Property value (if function, the value is passed into it and its return value is used as a new one)

    Returns 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

    • dimensions: Partial<TSize>

      Object with width/height properties

    • Optional options: TCanvasSizeOptions = {}

      Options object

    Returns void

  • Sets height of this canvas instance

    Parameters

    • value: number

      Value to set height to

    • Optional options: TCanvasSizeOptions = {}

      Options object

    Returns void

    Deprecated

    will be removed in 7.0

  • Private

    Set the canvas tolerance value for pixel taret find. Use only integer numbers.

    Parameters

    • value: number

    Returns void

  • Sets viewport transformation of this canvas instance

    Parameters

    • vpt: TMat2D

      a Canvas 2D API transform matrix

    Returns void

  • Sets width of this canvas instance

    Parameters

    • value: number

      Value to set width to

    • Optional options: TCanvasSizeOptions = {}

      Options object

    Returns void

    Deprecated

    will be removed in 7.0

  • Sets zoom level of this canvas instance

    Parameters

    • value: number

      to set zoom to, less than 1 zooms out

    Returns void

  • Returns a size of a collection (i.e: length of an array containing its objects)

    Returns number

    Collection size

  • 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

    Returns HTMLCanvasElement

  • Exports canvas element to a dataurl image. Note that when multiplier is used, cropping is scaled appropriately

    Parameters

    Returns string

    Returns a data: URL containing a representation of the object in the format specified by options.format

    See

    demo

    Example

    Generate jpeg dataURL with lower quality

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

    Example

    Generate cropped png dataURL (clipping of canvas)

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

    Example

    Generate double scaled png dataURL

    var dataURL = canvas.toDataURL({
    format: 'png',
    multiplier: 2
    });

    Example

    Generate dataURL with objects that overlap a specified object

    var myObject;
    var dataURL = canvas.toDataURL({
    filter: (object) => object.isContainedWithinObject(myObject) || object.intersectsWithObject(myObject)
    });
  • Returns dataless JSON representation of canvas

    Parameters

    • Optional propertiesToInclude: string[]

      Any properties that you might want to additionally include in the output

    Returns any

    json string

  • Returns dataless object representation of canvas

    Parameters

    • Optional propertiesToInclude: string[]

      Any properties that you might want to additionally include in the output

    Returns any

    object representation of an instance

  • 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)

    Returns any

    JSON compatible object

    Tutorial

    http://fabricjs.com/fabric-intro-part-3#serialization

    See

    demo

    Example

    JSON without additional properties

    var json = canvas.toJSON();
    

    Example

    JSON with additional properties included

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

    Example

    JSON without default values

    var json = canvas.toJSON();
    
  • Returns object representation of canvas

    Parameters

    • Optional propertiesToInclude: string[]

      Any properties that you might want to additionally include in the output

    Returns any

    object representation of an instance

  • Returns SVG representation of canvas

    Parameters

    • Optional options: TSVGExportOptions = {}

      Options object for SVG output

    • Optional reviver: TSVGReviver

      Method for further parsing of svg elements, called after each fabric object converted into svg representation.

    Returns string

    SVG string

    Function

    Tutorial

    http://fabricjs.com/fabric-intro-part-3#serialization

    See

    demo

    Example

    Normal SVG output

    var svg = canvas.toSVG();
    

    Example

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

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

    Example

    SVG output with viewBox attribute

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

    Example

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

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

    Example

    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; ', '');
    });
  • Returns a string representation of an instance

    Returns string

    string representation of an instance

  • Toggles specified property from true to false or from false to true

    Parameters

    • property: string

      Property to toggle

    Returns 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

    • point: Point

      to zoom with respect to

    • value: number

      to set zoom to, less than 1 zooms out

    Returns void

Generated using TypeDoc