Class IText<Props, SProps, EventSpec>

Fires

changed

Fires

selection:changed

Fires

editing:entered

Fires

editing:exited

Fires

dragstart

Fires

drag drag event firing on the drag source

Fires

dragend

Fires

copy

Fires

cut

Fires

paste

Supported key combinations

  Move cursor:                    left, right, up, down
Select character: shift + left, shift + right
Select text vertically: shift + up, shift + down
Move cursor by word: alt + left, alt + right
Select words: shift + alt + left, shift + alt + right
Move cursor to line start/end: cmd + left, cmd + right or home, end
Select till start/end of line: cmd + shift + left, cmd + shift + right or shift + home, shift + end
Jump to start/end of text: cmd + up, cmd + down
Select till start/end of text: cmd + shift + up, cmd + shift + down or shift + pgUp, shift + pgDown
Delete character: backspace
Delete word: alt + backspace
Delete line: cmd + backspace
Forward delete: delete
Copy text: ctrl/cmd + c
Paste text: ctrl/cmd + v
Cut text: ctrl/cmd + x
Select entire text: ctrl/cmd + a
Quit editing tab or esc

Supported mouse/touch combination

  Position cursor:                click/touch
Create selection: click/touch & drag
Create selection: click & shift + click
Select word: double click
Select line: triple click

Type Parameters

Hierarchy

  • ITextClickBehavior<Props, SProps, EventSpec>

Implements

  • UniqueITextProps

Constructors

Properties

CACHE_FONT_SIZE MIN_TEXT_WIDTH __charBounds __corner? __lineHeights __lineWidths __owningGroup? __selectionStartOnMouseDown _cacheCanvas? _cacheContext _controlsVisibility _currentCursorOpacity _fontSizeFraction _fontSizeMult _forceClearCache _reNewline _reSpace _reSpaceAndTab _reSpacesAndTabs _reWords _savedProps? _scaling? _selectionDirection _text _textLines _transformDone? _unwrappedTextLines aCoords absolutePositioned activeOn angle backgroundColor borderColor borderDashArray borderOpacityWhenMoving borderScaleFactor cacheHeight? cacheTranslationX? cacheTranslationY? cacheWidth? caching canvas? centeredRotation centeredScaling charSpacing clipPath? clipPathId? colorProperties compositionColor compositionEnd compositionStart controls cornerColor cornerDashArray cornerSize cornerStrokeColor cornerStyle ctrlKeysMapDown ctrlKeysMapUp cursorColor cursorDelay cursorDuration cursorOffsetCache cursorWidth deltaY direction dirty draggableTextDelegate editable editingBorderColor evented excludeFromExport fill fillRule flipX flipY fontFamily fontSize fontStyle fontWeight globalCompositeOperation group? hasBorders hasControls height hiddenTextarea hiddenTextareaContainer? hoverCursor inCompositionMode includeDefaultValues initialized? inverted isEditing isMoving? keysMap keysMapRtl left lineCoords lineHeight linethrough lockMovementX lockMovementY lockRotation lockScalingFlip lockScalingX lockScalingY lockSkewingX lockSkewingY matrixCache? minScaleLimit moveCursor noScaleCache oCoords objectCaching offsets opacity originX originY overline ownCaching? ownMatrixCache? padding paintFirst path? pathAlign pathSide pathStartOffset perPixelTargetFind scaleX scaleY selectable selected selectionBackgroundColor selectionColor selectionEnd selectionStart shadow skewX skewY snapAngle? snapThreshold? stroke strokeDashArray strokeDashOffset strokeLineCap strokeLineJoin strokeMiterLimit strokeUniform strokeWidth styles subscript superscript text textAlign textBackgroundColor textLines top touchCornerSize transparentCorners underline visible width zoomX? zoomY? ATTRIBUTE_NAMES _styleProperties cacheProperties genericFonts ownDefaults stateProperties textLayoutProperties type

Accessors

Methods

__getCursorBoundariesOffsets _animate _animateCursor _applyPatternForTransformedGradient _applyPatternGradientTransform _applyPatternGradientTransformText _calcTextareaPosition _calculateCurrentDimensions _clearCache _constrainScale _createBaseClipPathSVGMarkup _createBaseSVGMarkup _createCacheCanvas _deleteLineStyle _deleteStyleDeclaration _drawBorders _drawClipPath _exitEditing _findCenterFromElement _findTargetCorner _fireSelectionChanged _getCacheCanvasDimensions _getCurrentCharIndex _getCursorBoundaries _getCursorBoundariesOffsets _getFontDeclaration _getGraphemeBox _getIndexOnLine _getLeftOffset _getLeftTopCoords _getLineLeftOffset _getLineStyle _getNonTransformedDimensions _getSelectionForOffset _getStyleDeclaration _getTopOffset _getTransformedDimensions _getWidthBeforeCursor _getWidthOfCharSpacing _limitCacheSize _measureChar _measureLine _mouseDownHandler _mouseDownHandlerBefore _move _moveCursorLeftOrRight _moveCursorUpOrDown _moveLeft _moveRight _removeCacheCanvas _removeDefaultValues _removeExtraneousStyles _removeShadow _render _renderBackground _renderChar _renderChars _renderControls _renderCursor _renderFill _renderPaintInOrder _renderSelection _renderStroke _renderText _renderTextCommon _renderTextDecoration _renderTextFill _renderTextLine _renderTextLinesBackground _renderTextStroke _restoreEditingProps _saveEditingProps _set _setClippingProperties _setEditingProps _setFillStyles _setGraphemeOnPath _setLineDash _setLineStyle _setObject _setOpacity _setOptions _setScript _setShadow _setStrokeStyles _setStyleDeclaration _setTextStyles _setupCompositeOperation _splitText _splitTextIntoLines _toSVG _updateAndFire _updateCacheCanvas _updateTextarea abortCursorAnimation addPaintOrder animate blur calcACoords calcLineCoords calcOCoords calcOwnMatrix calcTextHeight calcTextWidth calcTransformMatrix canDrop cleanStyle clearContextTop clone cloneAsImage complexity containsPoint copy dispose doubleClickHandler drawBorders drawCacheOnCanvas drawClipPathOnCache drawControls drawControlsConnectingLines drawObject drawSelectionBackground enlargeSpaces enterEditing exitEditing findCommonAncestors findLineBoundaryLeft findLineBoundaryRight findWordBoundaryLeft findWordBoundaryRight fire forEachControl fromGraphemeToStringSelection fromStringToGraphemeSelection get get2DCursorLocation getActiveControl getAncestors getBoundingRect getCanvasRetinaScaling getCenterPoint getCompleteStyleDeclaration getCoords getCurrentCharColor getCurrentCharFontSize getDownCursorOffset getHeightOfChar getHeightOfLine getLineWidth getObjectOpacity getObjectScaling getParent getPointByOrigin getRelativeCenterPoint getRelativeX getRelativeXY getRelativeY getScaledHeight getScaledWidth getSelectedText getSelectionStartFromPointer getSelectionStyles getStyleAtPosition getSvgCommons getSvgFilter getSvgStyles getSvgTransform getTotalAngle getTotalObjectScaling getUpCursorOffset getValueOfPropertyAt getViewportTransform getX getXY getY graphemeSplit handleFiller hasCommonAncestors hasFill hasStroke initBehavior initDelayedCursor initDimensions initHiddenTextarea insertCharStyleObject insertChars insertNewStyleBlock insertNewlineStyleObject intersectsWithObject intersectsWithRect isCacheDirty isContainedWithinObject isContainedWithinRect isControlVisible isDescendantOf isEmptyStyles isEndOfWrapping isInFrontOf isNotVisible isOnScreen isOverlapping isPartiallyOnScreen isTripleClick isType measureLine missingNewlineOffset mouseUpHandler moveCursorDown moveCursorLeft moveCursorLeftWithShift moveCursorLeftWithoutShift moveCursorRight moveCursorRightWithShift moveCursorRightWithoutShift moveCursorUp moveCursorWithShift moveCursorWithoutShift needsItsOwnCache off on onCompositionEnd onCompositionStart onCompositionUpdate onDeselect onDragStart onInput onKeyDown onKeyUp onMouseDown onSelect once paste removeChars removeStyle removeStyleFromTo render renderCache renderCursor renderCursorAt renderCursorOrSelection renderDragSourceEffect renderDropTargetEffect renderSelection restartCursorIfNeeded rotate scale scaleToHeight scaleToWidth searchWordBoundary selectAll selectLine selectWord set setControlVisible setControlsVisibility setCoords setCursorByClick setOnGroup setOptions setPathInfo setPositionByOrigin setRelativeX setRelativeXY setRelativeY setSelectionEnd setSelectionStart setSelectionStartEndWithShift setSelectionStyles setSubscript setSuperscript setX setXY setY shiftLineStyles shouldCache shouldStartDragging strokeBorders styleHas toCanvasElement toClipPathSVG toDataURL toDatalessObject toJSON toObject toSVG toString toggle transform transformMatrixKey translateToCenterPoint translateToGivenOrigin translateToOriginPoint tripleClickHandler updateFromTextArea updateSelectionOnMouseMove updateTextareaPosition willDrawShadow _fromObject fromElement fromObject getDefaults

Constructors

  • Constructor

    Type Parameters

    Parameters

    • text: string

      Text string

    • Optional options: Props

      Options object

    Returns IText<Props, SProps, EventSpec>

Properties

CACHE_FONT_SIZE: number

use this size when measuring text. To avoid IE11 rounding errors

Default

@readonly
@private
MIN_TEXT_WIDTH: number

contains the min text width to avoid getting 0

Default


__charBounds: GraphemeBBox[][] = []

contains characters bounding boxes This variable is considered to be protected. But for how mixins are implemented right now, we can't leave it private

__corner?: string

keeps the value of the last hovered corner during mouse move. 0 is no corner, or 'mt', 'ml', 'mtr' etc.. It should be private, but there is no harm in using it as a read-only property. this isn't cleaned automatically. Non selected objects may have wrong values

__lineHeights: number[]
__lineWidths: number[]
__owningGroup?: Group

A reference to the parent of the object Used to keep the original parent ref when the object has been added to an ActiveSelection, hence loosing the group ref

__selectionStartOnMouseDown: number
_cacheCanvas?: HTMLCanvasElement

A reference to the HTMLCanvasElement that is used to contain the cache of the object this canvas element is resized and cleared as needed Is marked private, you can read it, don't use it since it is handled by fabric since 1.7.0

Default

undefined
@private
_cacheContext: null | CanvasRenderingContext2D = null

Quick access for the _cacheCanvas rendering context This is part of the objectCaching feature since 1.7.0

Default

undefined
@private
_controlsVisibility: Record<string, boolean>

a map of control visibility for this object. this was left when controls were introduced to not break the api too much this takes priority over the generic control visibility

_currentCursorOpacity: number = 1
_fontSizeFraction: number
_fontSizeMult: number

Text Line proportion to font Size (in pixels)

Default


_forceClearCache: boolean
_reNewline: RegExp
_reSpace: RegExp
_reSpaceAndTab: RegExp

Use this regular expression to filter for whitespace that is not a new line. Mostly used when text is 'justify' aligned.

_reSpacesAndTabs: RegExp

Use this regular expression to filter for whitespaces that is not a new line. Mostly used when text is 'justify' aligned.

_reWords: RegExp

Use this regular expression to filter consecutive groups of non spaces. Mostly used when text is 'justify' aligned.

_savedProps?: {
    borderColor: string;
    defaultCursor?: string;
    hasControls: boolean;
    hoverCursor: null | string;
    lockMovementX: boolean;
    lockMovementY: boolean;
    moveCursor?: string;
    selectable: boolean;
}

Type declaration

  • borderColor: string
  • Optional defaultCursor?: string
  • hasControls: boolean
  • hoverCursor: null | string
  • lockMovementX: boolean
  • lockMovementY: boolean
  • Optional moveCursor?: string
  • selectable: boolean
_scaling?: boolean

A boolean used from the gesture module to keep tracking of a scaling action when there is no scaling transform in place. This is an edge case and is used twice in all codebase. Probably added to keep track of some performance issues

TODO

use git blame to investigate why it was added DON'T USE IT. WE WILL TRY TO REMOVE IT

_selectionDirection: null | "left" | "right"
_text: string[]
_textLines: string[][]

same as textlines, but each line is an array of graphemes as split by splitByGrapheme

Default


_transformDone?: boolean

Private. indicates if the object inside a group is on a transformed context or not or is part of a larger cache for many object ( a group for example)

Default

undefined
@private
_unwrappedTextLines: string[][]
aCoords: TCornerPoint

Describe object's corner position in canvas object absolute coordinates properties are tl,tr,bl,br and describe the four main corner. each property is an object with x, y, instance of Fabric.Point. The coordinates depends from this properties: width, height, scaleX, scaleY skewX, skewY, angle, strokeWidth, top, left. Those coordinates are useful to understand where an object is. They get updated with lineCoords or oCoords in interactive cases but they do not need to be updated when zoom or panning change. The coordinates get updated with

Method

setCoords. You can calculate them without updating with

Method

calcACoords();

absolutePositioned: boolean
activeOn: "down" | "up"
angle: TDegree
backgroundColor: string
borderColor: string
borderDashArray: null | number[]
borderOpacityWhenMoving: number
borderScaleFactor: number
cacheHeight?: number

Size of the cache canvas, height since 1.7.0

Default

undefined
@private
cacheTranslationX?: number

zoom level used on the cacheCanvas to draw the cache, Y axe since 1.7.0

Default

undefined
@private
cacheTranslationY?: number

translation of the cacheCanvas away from the center, for subpixel accuracy and crispness since 1.7.0

Default

undefined
@private
cacheWidth?: number

Size of the cache canvas, width since 1.7.0

Default

undefined
@private
caching: boolean

Indicates whether internal text char widths can be cached

Default


canvas?: Canvas
centeredRotation: boolean
centeredScaling: boolean
charSpacing: number

additional space between characters expressed in thousands of em unit

Default


clipPath?: FabricObject<Partial<ObjectProps>, SerializedObjectProps, ObjectEvents>
clipPathId?: string

When an object is being exported as SVG as a clippath, a reference inside the SVG is needed. This reference is a UID in the fabric namespace and is temporary stored here.

colorProperties: string[]

List of properties to consider for animating colors.

compositionColor: string
compositionEnd: number
compositionStart: number
controls: TControlSet

holds the controls for the object. controls are added by default_controls.js

cornerColor: string
cornerDashArray: null | number[]
cornerSize: number
cornerStrokeColor: string
cornerStyle: "circle" | "rect"
ctrlKeysMapDown: TKeyMapIText

For functionalities on keyDown + ctrl || cmd

ctrlKeysMapUp: TKeyMapIText

For functionalities on keyUp + ctrl || cmd

cursorColor: string

Color of text cursor color in editing mode. if not set (default) will take color from the text. if set to a color value that fabric can understand, it will be used instead of the color of the text at the current position.

Default


cursorDelay: number

Delay between cursor blink (in ms)

Default


cursorDuration: number

Duration of cursor fade in (in ms)

Default


cursorOffsetCache: {
    left?: number;
    top?: number;
}

Type declaration

  • Optional left?: number
  • Optional top?: number
cursorWidth: number

Width of cursor (in px)

Default


deltaY: number

Baseline shift, styles only, keep at 0 for the main text object

Default


direction: CanvasDirection

WARNING: EXPERIMENTAL. NOT SUPPORTED YET determine the direction of the text. This has to be set manually together with textAlign and originX for proper experience. some interesting link for the future https://www.w3.org/International/questions/qa-bidi-unicode-controls

Since

4.5.0

Default


dirty: boolean

When set to true, object's cache will be rerendered next render call. since 1.7.0

Default

true
draggableTextDelegate: DraggableTextDelegate
editable: boolean

Indicates whether a text can be edited

Default


editingBorderColor: string

Border color of text object while it's in editing mode

Default


evented: boolean
excludeFromExport: boolean
fill: null | string | TFiller
fillRule: CanvasFillRule
flipX: boolean
flipY: boolean
fontFamily: string

Font family

Default


fontSize: number

Font size (in pixels)

Default


fontStyle: string

Font style . Possible values: "", "normal", "italic" or "oblique".

Default


fontWeight: string

Font weight (e.g. bold, normal, 400, 600, 800)

Default


globalCompositeOperation: GlobalCompositeOperation
group?: Group

A reference to the parent of the object, usually a Group

Default

undefined
@private
hasBorders: boolean
hasControls: boolean
height: number
hiddenTextarea: null | HTMLTextAreaElement
hiddenTextareaContainer?: null | HTMLElement

DOM container to append the hiddenTextarea. An alternative to attaching to the document.body. Useful to reduce laggish redraw of the full document.body tree and also with modals event capturing that won't let the textarea take focus.

Default


hoverCursor: null | string
inCompositionMode: boolean

Helps determining when the text is in composition, so that the cursor rendering is altered.

includeDefaultValues: boolean
initialized?: true
inverted: boolean
isEditing: boolean

Indicates whether text is in editing mode

Default


isMoving?: boolean

internal boolean to signal the code that the object is part of the move action.

keysMap: TKeyMapIText

For functionalities on keyDown Map a special key to a function of the instance/prototype If you need different behavior for ESC or TAB or arrows, you have to change this map setting the name of a function that you build on the IText or your prototype. the map change will affect all Instances unless you need for only some text Instances in that case you have to clone this object and assign your Instance. this.keysMap = Object.assign({}, this.keysMap); The function must be in IText.prototype.myFunction And will receive event as args[0]

keysMapRtl: TKeyMapIText
left: number
lineCoords: TCornerPoint

Describe object's corner position in canvas element coordinates. includes padding. Used of object detection. set and refreshed with setCoords. Those could go away

Todo

investigate how to get rid of those

lineHeight: number

Line height

Default


linethrough: boolean

Text decoration linethrough.

Default


lockMovementX: boolean
lockMovementY: boolean
lockRotation: boolean
lockScalingFlip: boolean
lockScalingX: boolean
lockScalingY: boolean
lockSkewingX: boolean
lockSkewingY: boolean
matrixCache?: TMatrixCache

storage cache for object full transform matrix

minScaleLimit: number
moveCursor: null | string
noScaleCache: boolean
oCoords: Record<string, TOCoord>

Describe object's corner position in canvas element coordinates. properties are depending on control keys and padding the main controls. each property is an object with x, y and corner. The corner property contains in a similar manner the 4 points of the interactive area of the corner. The coordinates depends from the controls positionHandler and are used to draw and locate controls

objectCaching: boolean
offsets: {
    linethrough: number;
    overline: number;
    underline: number;
}

Type declaration

  • linethrough: number
  • overline: number
  • underline: number
opacity: number
originX: TOriginX
originY: TOriginY
overline: boolean

Text decoration overline.

Default


ownCaching?: boolean

Indicate if the object is sitting on a cache dedicated to it or is part of a larger cache for many object ( a group for example)

Default

undefined
@private
ownMatrixCache?: TMatrixCache

storage cache for object transform matrix

padding: number
paintFirst: "fill" | "stroke"

Path that the text should follow. since 4.6.0 the path will be drawn automatically. if you want to make the path visible, give it a stroke and strokeWidth or fill value if you want it to be hidden, assign visible = false to the path. This feature is in BETA, and SVG import/export is not yet supported.

Example

const textPath = new Text('Text on a path', {
top: 150,
left: 150,
textAlign: 'center',
charSpacing: -50,
path: new Path('M 0 0 C 50 -100 150 -100 200 0', {
strokeWidth: 1,
visible: false
}),
pathSide: 'left',
pathStartOffset: 0
});

Default


pathAlign: TPathAlign

How text is aligned to the path. This property determines the perpendicular position of each character relative to the path. (one of "baseline", "center", "ascender", "descender") This feature is in BETA, and its behavior may change

Default


pathSide: TPathSide

Which side of the path the text should be drawn on. Only used when text has a path

Default


pathStartOffset: number

Offset amount for text path starting position Only used when text has a path

Default


perPixelTargetFind: boolean
scaleX: number
scaleY: number
selectable: boolean
selected: boolean
selectionBackgroundColor: string
selectionColor: string

Color of text selection

Default


selectionEnd: number

Index where text selection ends

Default


selectionStart: number

Index where text selection starts (or where cursor is when there is no selection)

Default


shadow: null | Shadow
skewX: number
skewY: number
snapAngle?: TDegree
snapThreshold?: TDegree
stroke: null | string | TFiller
strokeDashArray: null | number[]
strokeDashOffset: number
strokeLineCap: CanvasLineCap
strokeLineJoin: CanvasLineJoin
strokeMiterLimit: number
strokeUniform: boolean
strokeWidth: number
styles: TextStyle
subscript: {
    baseline: number;
    size: number;
}

Subscript schema object (minimum overlap)

Type declaration

  • baseline: number

    baseline-shift factor (downwards)

    Default

    0.11
    
  • size: number

    fontSize factor

    Default

    0.6
    
superscript: {
    baseline: number;
    size: number;
}

Superscript schema object (minimum overlap)

Type declaration

  • baseline: number

    baseline-shift factor (upwards)

    Default

    -0.35
    
  • size: number

    fontSize factor

    Default

    0.6
    
text: string
textAlign: string

Text alignment. Possible values: "left", "center", "right", "justify", "justify-left", "justify-center" or "justify-right".

Default


textBackgroundColor: string

Background color of text lines

Default


textLines: string[]

contains the the text of the object, divided in lines as they are displayed on screen. Wrapping will divide the text independently of line breaks

Default


top: number
touchCornerSize: number
transparentCorners: boolean
underline: boolean

Text decoration underline.

Default


visible: boolean
width: number
zoomX?: number

zoom level used on the cacheCanvas to draw the cache, X axe since 1.7.0

Default

undefined
@private
zoomY?: number

zoom level used on the cacheCanvas to draw the cache, Y axe since 1.7.0

Default

undefined
@private
ATTRIBUTE_NAMES: string[] = ...

List of attribute names to account for when parsing SVG element (used by FabricText.fromElement)

_styleProperties: readonly StylePropertiesType[] = styleProperties
cacheProperties: string[] = ...
genericFonts: string[] = ...
ownDefaults: Record<string, any> = iTextDefaultValues
stateProperties: string[] = stateProperties

This list of properties is used to check if the state of an object is changed. This state change now is only used for children of groups to understand if a group needs its cache regenerated during a .set call

textLayoutProperties: string[] = textLayoutProperties

Properties that requires a text layout recalculation when changed

type: string = 'IText'

Accessors

Methods

  • Private

    Calculates cursor left/top offset relative to instance's center point

    Parameters

    • index: number

      index from start

    Returns {
        left: number;
        top: number;
    }

    • left: number
    • top: number
  • Private

    Parameters

    • __namedParameters: {
          delay?: number;
          duration: number;
          onComplete?: TOnAnimationChangeCallback<number, void>;
          toValue: number;
      }

    Returns ValueAnimation

  • Private

    This function try to patch the missing gradientTransform on canvas gradients. transforming a context to transform the gradient, is going to transform the stroke too. we want to transform the gradient but not the stroke operation, so we create a transformed gradient on a pattern and then we use the pattern instead of the gradient. this method has drawbacks: is slow, is in low resolution, needs a patch for when the size is limited.

    Parameters

    • ctx: CanvasRenderingContext2D

      Context to render on

    • filler: TFiller

    Returns void

  • Private

    Parameters

    Returns {
        offsetX: number;
        offsetY: number;
    }

    • offsetX: number
    • offsetY: number
  • Private

    This function try to patch the missing gradientTransform on canvas gradients. transforming a context to transform the gradient, is going to transform the stroke too. we want to transform the gradient but not the stroke operation, so we create a transformed gradient on a pattern and then we use the pattern instead of the gradient. this method has drawbacks: is slow, is in low resolution, needs a patch for when the size is limited.

    Parameters

    • filler: TFiller

      a fabric gradient instance

    Returns CanvasPattern

    a pattern to use as fill/stroke style

  • Private

    Returns {
        charHeight?: undefined;
        fontSize?: undefined;
        left: string;
        top: string;
    } | {
        charHeight: number;
        fontSize: string;
        left: string;
        top: string;
    }

    style contains style for hiddenTextarea

  • Private

    Calculate object dimensions for controls box, including padding and canvas zoom. and active selection

    Parameters

    • Optional options: any

      transform options

    Returns Point

    dimensions

  • Private

    Makes sure the scale is valid and modifies it if necessary @todo: this is a control action issue, not a geometry one

    Parameters

    • value: number

    Returns number

    constrained value;

  • Private

    Create a the canvas used to keep the cached copy of the object

    Returns void

  • Parameters

    • lineIndex: number

    Returns void

  • Private

    Parameters

    • lineIndex: number
    • charIndex: number

    Returns void

  • Private

    Parameters

    • ctx: CanvasRenderingContext2D

      Context to draw on

    • size: Point
    • styleOverride: TStyleOverride = {}

      object to override the object style

    Returns void

  • Prepare clipPath state and cache and draw it on instance's cache

    Parameters

    Returns void

  • Private

    This function is an helper for svg import. it returns the center of the object in the svg untransformed coordinates

    Returns Point

    center point from element coordinates

  • Private

    Determines which corner is under the mouse cursor, represented by pointer. This function is return a corner only if the object is the active one. This is done to avoid selecting corner of non active object and activating transformations rather than drag action. The default behavior of fabricJS is that if you want to transform an object, first you select it to show the control set

    Parameters

    • pointer: Point

      The pointer indicating the mouse position

    • forTouch: boolean = false

      indicates if we are looking for interaction area with a touch action

    Returns string

    corner code (tl, tr, bl, br, etc.), or 0 if nothing is found.

  • Private

    Fires the even of selection changed

    Returns void

  • Private

    Returns the cursor position for the getCurrent.. functions

    Returns {
        c: number;
        l: number;
    }

    • c: number
    • l: number
  • Private

    Returns cursor boundaries (left, top, leftOffset, topOffset) left/top are left/top of entire text box leftOffset/topOffset are offset from that left/top point of a text box

    Parameters

    • Optional index: number = ...

      index from start

    • Optional skipCaching: boolean

    Returns CursorBoundaries

  • Private

    Caches and returns cursor left/top offset relative to instance's center point

    Parameters

    • index: number

      index from start

    • Optional skipCaching: boolean

    Returns {
        left: number;
        top: number;
    }

    • left: number
    • top: number
  • return font declaration string for canvas context

    Parameters

    • Optional __namedParameters: Partial<Pick<Partial<CompleteTextStyleDeclaration>, "fontFamily" | "fontSize" | "fontStyle" | "fontWeight">> = {}
    • Optional forMeasuring: boolean

    Returns string

    font declaration formatted for canvas context.

  • Parameters

    • grapheme: string

      to be measured

    • lineIndex: number

      index of the line where the char is

    • charIndex: number

      position in the line

    • Optional prevGrapheme: string

      character preceding the one to be measured

    • Optional skipLeft: boolean

    Returns GraphemeBBox

    grapheme bbox

  • Private

    for a given width it founds the matching character.

    Parameters

    • lineIndex: number
    • width: number

    Returns number

  • Private

    Returns number

    Left offset

  • Private

    Parameters

    • lineIndex: number

      index text line

    Returns number

    Line left offset

  • Private

    Parameters

    • lineIndex: number

    Returns boolean

    if the line exists or not

  • private Helps finding if the offset should be counted from Start or End

    Parameters

    • e: KeyboardEvent

      Event object

    • isRight: boolean

    Returns number

  • get the reference, not a clone, of the style object for a given character, if not style is set for a pre det

    Parameters

    • lineIndex: number
    • charIndex: number

    Returns Partial<CompleteTextStyleDeclaration>

    style object a REFERENCE to the existing one or a new empty object

  • Private

    Returns number

    Top offset

  • Private

    Calculate object bounding box dimensions from its properties scale, skew.

    Parameters

    • Optional options: any = {}

    Returns Point

    dimensions

  • Private

    Finds the width in pixels before the cursor on the same line

    Parameters

    • lineIndex: number
    • charIndex: number

    Returns number

    widthBeforeCursor width before cursor

  • Returns number

  • Limit the cache dimensions so that X * Y do not cross config.perfLimitSizeTotal and each side do not cross fabric.cacheSideLimit those numbers are configurable so that you can get as much detail as you want making bargain with performances.

    Parameters

    • dims: any

    Returns any

    .width width of canvas

  • Private

    measure and return the width of a single character. possibly overridden to accommodate different measure logic or to hook some external lib for character measurement

    Parameters

    Returns {
        kernedWidth: number;
        width: number;
    }

    • kernedWidth: number
    • width: number
  • measure every grapheme of a line, populating __charBounds

    Parameters

    • lineIndex: number

    Returns {
        numOfSpaces: number;
        width: number;
    }

    object.width total width of characters

    • numOfSpaces: number
    • width: number
  • Default event handler for the basic functionalities needed on _mouseDown can be overridden to do something different. Scope of this implementation is: find the click position, set selectionStart find selectionEnd, initialize the drawing of either cursor or selection area initializing a mousedDown on a text area will cancel fabricjs knowledge of current compositionMode. It will be set to false.

    Parameters

    Returns void

  • Default event handler for the basic functionalities needed on mousedown:before can be overridden to do something different. Scope of this implementation is: verify the object is already selected when mousing down

    Parameters

    Returns void

  • Private

    Parameters

    • e: KeyboardEvent
    • prop: "selectionStart" | "selectionEnd"
    • direction: "Left" | "Right"

    Returns boolean

    true if a change happened

    Todo

    refactor not to use method name composition

  • Moves cursor right or Left, fires event

    Parameters

    • direction: "Left" | "Right"

      'Left', 'Right'

    • e: KeyboardEvent

      Event object

    Returns void

  • Moves cursor up or down, fires the events

    Parameters

    • direction: "Up" | "Down"

      'Up' or 'Down'

    • e: KeyboardEvent

      Event object

    Returns void

  • Private

    Parameters

    • e: KeyboardEvent
    • prop: "selectionStart" | "selectionEnd"

    Returns boolean

  • Private

    Parameters

    • e: KeyboardEvent
    • prop: "selectionStart" | "selectionEnd"

    Returns boolean

  • Remove cacheCanvas and its dimensions from the objects

    Returns void

  • Private

    Type Parameters

    • T extends object

    Parameters

    • object: T

    Returns Partial<T>

  • Private

    Parameters

    • ctx: CanvasRenderingContext2D

      Context to render on

    Returns void

  • Private

    Parameters

    • ctx: CanvasRenderingContext2D

      Context to render on

    Returns void

  • Private

    Draws a background for the object big as its untransformed dimensions

    Parameters

    • ctx: CanvasRenderingContext2D

      Context to render on

    Returns void

  • Private

    Parameters

    • method: "fillText" | "strokeText"
    • ctx: CanvasRenderingContext2D

      Context to render on

    • lineIndex: number
    • charIndex: number
    • _char: string
    • left: number

      Left coordinate

    • top: number

      Top coordinate

    Returns void

  • Private

    Parameters

    • method: "fillText" | "strokeText"

      fillText or strokeText.

    • ctx: CanvasRenderingContext2D

      Context to render on

    • line: any[]

      Content of the line, splitted in an array by grapheme

    • left: number
    • top: number
    • lineIndex: number

    Returns void

  • Renders controls and borders for the object the context here is not transformed

    Parameters

    • ctx: CanvasRenderingContext2D

      Context to render on

    • Optional styleOverride: TStyleOverride = {}

      properties to override the object style

    Returns void

    Todo

    move to interactivity

  • Parameters

    • ctx: CanvasRenderingContext2D
    • boundaries: CursorBoundaries
    • selectionStart: number

    Returns void

  • Private

    Parameters

    • ctx: CanvasRenderingContext2D

      Context to render on

    Returns void

  • Private

    Parameters

    • ctx: CanvasRenderingContext2D

      Context to render on

    Returns void

  • Private

    Renders text selection

    Parameters

    • ctx: CanvasRenderingContext2D

      transformed context to draw on

    • selection: {
          selectionEnd: number;
          selectionStart: number;
      }
      • selectionEnd: number
      • selectionStart: number
    • boundaries: CursorBoundaries

      Object with left/top/leftOffset/topOffset

    Returns void

  • Private

    Parameters

    • ctx: CanvasRenderingContext2D

      Context to render on

    Returns void

  • Private

    Parameters

    • ctx: CanvasRenderingContext2D

      Context to render on

    Returns void

  • Private

    Parameters

    • ctx: CanvasRenderingContext2D

      Context to render on

    • method: "fillText" | "strokeText"

      Method name ("fillText" or "strokeText")

    Returns void

  • Private

    Parameters

    • ctx: CanvasRenderingContext2D

      Context to render on

    • type: "underline" | "overline" | "linethrough"

    Returns void

  • Private

    Parameters

    • ctx: CanvasRenderingContext2D

      Context to render on

    Returns void

  • Private

    Parameters

    • method: "fillText" | "strokeText"

      Method name ("fillText" or "strokeText")

    • ctx: CanvasRenderingContext2D

      Context to render on

    • line: string[]

      Text to render

    • left: number

      Left position of text

    • top: number

      Top position of text

    • lineIndex: number

      Index of a line in a text

    Returns void

  • Private

    Renders the text background for lines, taking care of style

    Parameters

    • ctx: CanvasRenderingContext2D

      Context to render on

    Returns void

  • Private

    Parameters

    • ctx: CanvasRenderingContext2D

      Context to render on

    Returns void

  • Private

    While editing handle differently

    Parameters

    • key: string
    • value: any

    Returns IText<Props, SProps, EventSpec>

  • Parameters

    • ctx: CanvasRenderingContext2D

    Returns void

  • This function prepare the canvas for a ill style, and fill need to be sent in as defined

    Parameters

    • ctx: CanvasRenderingContext2D
    • style: Pick<IText<Props, SProps, EventSpec>, "fill">

      with ill defined

    Returns {
        offsetX: number;
        offsetY: number;
    }

    • offsetX: number
    • offsetY: number
  • Private

    Calculate the angle and the left,top position of the char that follow a path. It appends it to graphemeInfo to be reused later at rendering

    Parameters

    • positionInPath: number

      to be measured

    • graphemeInfo: GraphemeBBox

      current grapheme box information

    Returns void

  • Private

    Sets line dash

    Parameters

    • ctx: CanvasRenderingContext2D

      Context to set the dash line on

    • Optional dashArray: null | number[]

      array representing dashes

    Returns void

  • Private

    Set the line style to an empty object so that is initialized

    Parameters

    • lineIndex: number

    Returns void

  • Private

    Parameters

    • obj: Record<string, any>

    Returns void

  • Private

    Parameters

    • ctx: CanvasRenderingContext2D

      Context to render on

    Returns void

  • Protected

    Sets object's properties from options, for initialization only

    Parameters

    • Optional options: any = {}

      Options object

    Returns void

  • Private

    Applies 'schema' at given position

    Parameters

    • start: number

      selection start

    • end: number

      selection end

    • schema: {
          baseline: number;
          size: number;
      }
      • baseline: number
      • size: number

    Returns void

  • Private

    Parameters

    • ctx: CanvasRenderingContext2D

      Context to render on

    Returns void

  • This function prepare the canvas for a stroke style, and stroke and strokeWidth need to be sent in as defined

    Parameters

    Returns {
        offsetX: number;
        offsetY: number;
    }

    • offsetX: number
    • offsetY: number
  • Private

    Parameters

    • lineIndex: number
    • charIndex: number
    • style: object

    Returns void

  • Private

    Set the font parameter of the context with the object properties or with charStyle

    Parameters

    • ctx: CanvasRenderingContext2D

      Context to render on

    • Optional charStyle: any

      object with font style properties

    • Optional forMeasuring: boolean

    Returns void

  • Sets canvas globalCompositeOperation for specific object custom composition operation for the particular object can be specified using globalCompositeOperation property

    Parameters

    • ctx: CanvasRenderingContext2D

      Rendering canvas context

    Returns void

  • Private

    Divides text into lines of text and lines of graphemes.

    Returns TextLinesInfo

  • Returns the text as an array of lines.

    Parameters

    • text: string

      text to split

    Returns TextLinesInfo

    Lines in the text

  • Returns svg representation of an instance This function is implemented in each subclass This is just because typescript otherwise cryies all the time

    Parameters

    Returns string[]

    an array of strings with the specific svg representation of the instance

  • Private

    Parameters

    • property: "selectionStart" | "selectionEnd"

      'selectionStart' or 'selectionEnd'

    • index: number

      new position of property

    Returns void

  • Private

    Update width and height of the canvas for cache returns true or false if canvas needed resize.

    Returns boolean

    true if the canvas has been resized

  • Aborts cursor animation, clears all timeouts and clear textarea context if necessary

    Returns void

  • Calculates the coordinates of the center of each control plus the corners of the control itself This basically just delegates to each control positionHandler WARNING: changing what is passed to positionHandler is a breaking change, since position handler is a public api and should be done just if extremely necessary

    Returns Record<string, TOCoord>

  • calculate transform matrix that represents the current transformations from the object's properties, this matrix does not include the group transformation

    Returns TMat2D

    transform matrix for the object

  • Calculate text box height

    Returns number

  • Private

    calculate and return the text Width measuring each line.

    Returns number

    Maximum width of Text object

  • calculate transform matrix that represents the current transformations from the object's properties.

    Parameters

    • Optional skipGroup: boolean = false

      return transform matrix for object not counting parent transformations There are some situation in which this is useful to avoid the fake rotation.

    Returns TMat2D

    transform matrix for the object

  • override this method to control whether instance should/shouldn't become a drop target

    Parameters

    • e: DragEvent

    Returns boolean

  • Check if characters in a text have a value for a property whose value matches the textbox's value for that property. If so, the character-level property is deleted. If the character has no other properties, then it is also deleted. Finally, if the line containing that character has no other characters then it also is deleted.

    Parameters

    • property: StylePropertiesType

      The property to compare between characters and text.

    Returns undefined | false

  • Clears the canvas.contextTop in a specific area that corresponds to the object's bounding box that is in the canvas.contextContainer. This function is used to clear pieces of contextTop where we render ephemeral effects on top of the object. Example: blinking cursor text selection, drag effects.

    Parameters

    • Optional restoreManually: boolean

      When true won't restore the context after clear, in order to draw something else.

    Returns undefined | CanvasRenderingContext2D

    canvas.contextTop that is either still transformed with the object transformMatrix, or restored to neutral transform

    Todo

    discuss swapping restoreManually with a renderCallback, but think of async issues

  • Clones an instance.

    Parameters

    • Optional propertiesToInclude: string[]

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

    Returns Promise<IText<Props, SProps, EventSpec>>

  • Creates an instance of Image out of an object makes use of toCanvasElement. Once this method was based on toDataUrl and loadImage, so it also had a quality and format option. toCanvasElement is faster and produce no loss of quality. If you need to get a real Jpeg or Png from an object, using toDataURL is the right way to do it. toCanvasElement and then toBlob from the obtained canvas is also a good option.

    Parameters

    • Optional options: any

      for clone as image, passed to toDataURL

    Returns FabricImage<Partial<ImageProps>, SerializedImageProps, ObjectEvents>

    Object cloned as image.

    Todo

    fix the export type, it could not be Image but the type that getClass return for 'image'.

  • Returns complexity of an instance

    Returns number

    complexity

  • Checks if point is inside the object

    Parameters

    • point: Point

      Point to check against

    • Optional absolute: boolean = false

      use coordinates without viewportTransform

    • Optional calculate: boolean = false

      use coordinates of current position instead of stored ones

    Returns boolean

    true if point is inside the object

  • Draws borders of an object's bounding box. Requires public properties: width, height Requires public options: padding, borderColor

    Parameters

    • ctx: CanvasRenderingContext2D

      Context to draw on

    • options: Required<Omit<TComposeMatrixArgs, "flipX" | "flipY">>

      object representing current object parameters

    • Optional styleOverride: TStyleOverride

      object to override the object style

    Returns void

  • Paint the cached copy of the object on the target context.

    Parameters

    Returns void

  • Execute the drawing operation for an object clipPath

    Parameters

    Returns void

  • Draws corners of an object's bounding box. Requires public properties: width, height Requires public options: cornerSize, padding

    Parameters

    • ctx: CanvasRenderingContext2D

      Context to draw on

    • styleOverride: Partial<Pick<InteractiveFabricObject<Partial<FabricObjectProps>, SerializedObjectProps, ObjectEvents>, "cornerStyle" | "cornerSize" | "cornerColor" | "cornerStrokeColor" | "cornerDashArray" | "transparentCorners">> = {}

      object to override the object style

    Returns void

  • Draws lines from a borders of an object's bounding box to controls that have withConnection property set. Requires public properties: width, height Requires public options: padding, borderColor

    Parameters

    • ctx: CanvasRenderingContext2D

      Context to draw on

    • size: Point

      object size x = width, y = height

    Returns void

  • Execute the drawing operation for an object on a specified context

    Parameters

    • ctx: CanvasRenderingContext2D

      Context to render on

    • Optional forClipping: boolean

      apply clipping styles

    Returns void

  • Draws a colored layer behind the object, inside its selection borders. Requires public options: padding, selectionBackgroundColor this function is called when the context is transformed has checks to be skipped when the object is on a staticCanvas

    Parameters

    • ctx: CanvasRenderingContext2D

      Context to draw on

    Returns void

    Todo

    evaluate if make this disappear in favor of a pre-render hook for objects this was added by Andrea Bogazzi to make possible some feature for work reasons it seemed a good option, now is an edge case

  • Enlarge space boxes and shift the others

    Returns void

  • Compare ancestors

    Type Parameters

    • T extends IText<Props, SProps, EventSpec, T>

    • S extends boolean

    Parameters

    • other: T
    • Optional strict: S

      finds only ancestors that are objects (without canvas)

    Returns AncestryComparison<S>

    an object that represent the ancestry situation.

  • Find new selection index representing start of current line according to current selection index

    Parameters

    • startFrom: number

      Current selection index

    Returns number

    New selection index

  • Find new selection index representing end of current line according to current selection index

    Parameters

    • startFrom: number

      Current selection index

    Returns number

    New selection index

  • Find new selection index representing start of current word according to current selection index

    Parameters

    • startFrom: number

      Current selection index

    Returns number

    New selection index

  • Find new selection index representing end of current word according to current selection index

    Parameters

    • startFrom: number

      Current selection index

    Returns number

    New selection index

  • Fires event with an optional options object

    Type Parameters

    • K extends string | number | symbol

    Parameters

    • eventName: K

      Event name to fire

    • Optional options: EventSpec[K]

      Options object

    Returns void

  • Calls a function for each control. The function gets called, with the control, the control's key and the object that is calling the iterator

    Parameters

    Returns void

  • convert from fabric to textarea values

    Parameters

    • start: number
    • end: number
    • graphemes: string[]

    Returns {
        selectionEnd: number;
        selectionStart: number;
    }

    • selectionEnd: number
    • selectionStart: number
  • convert from textarea to grapheme indexes

    Parameters

    • start: number
    • end: number
    • text: string

    Returns {
        selectionEnd: number;
        selectionStart: number;
    }

    • selectionEnd: number
    • selectionStart: number
  • Basic getter

    Parameters

    • property: string

      Property name

    Returns any

    value of a property

  • Returns 2d representation (lineIndex and charIndex) of cursor (or selection start)

    Parameters

    • Optional selectionStart: number = ...

      Optional index. When not given, current selectionStart is used.

    • Optional skipWrapping: boolean

      consider the location for unwrapped lines. useful to manage styles.

    Returns {
        charIndex: number;
        lineIndex: number;
    }

    • charIndex: number
    • lineIndex: number
  • Type Parameters

    • T extends boolean

    Parameters

    • Optional strict: T

      returns only ancestors that are objects (without canvas)

    Returns Ancestors<T>

    ancestors (excluding ActiveSelection) from bottom to top

  • Returns coordinates of object's bounding rectangle (left, top, width, height) the box is intended as aligned to axis of canvas.

    Parameters

    • Optional absolute: boolean

      use coordinates without viewportTransform

    • Optional calculate: boolean

      use coordinates of current position instead of .lineCoords / .aCoords

    Returns TBBox

    Object with left, top, width, height properties

  • return a new object that contains all the style property for a character the object returned is newly created

    Parameters

    • lineIndex: number

      of the line where the character is

    • charIndex: number

      position of the character on the line

    Returns CompleteTextStyleDeclaration

    style object

  • return correct set of coordinates for intersection this will return either aCoords or lineCoords. The coords are returned in an array.

    Parameters

    • absolute: boolean = false

      will return aCoords if true or lineCoords

    • calculate: boolean = false

      will return aCoords if true or lineCoords

    Returns Point[]

    [tl, tr, br, bl] of points

  • High level function to know the color of the cursor. the currentChar is the one that precedes the cursor Returns color (fill) of char at the current cursor if the text object has a pattern or gradient for filler, it will return that. Unused by the library, is for the end user

    Returns null | string | TFiller

    Character color (fill)

  • High level function to know the height of the cursor. the currentChar is the one that precedes the cursor Returns fontSize of char at the current cursor Unused from the library, is for the end user

    Returns number

    Character font size

  • Gets start offset of a selection

    Parameters

    • e: KeyboardEvent

      Event object

    • isRight: boolean

    Returns number

  • Computes height of character at given position

    Parameters

    • line: number

      the line index number

    • _char: number

      the character index number

    Returns number

    fontSize of the character

  • Calculate height of line at 'lineIndex'

    Parameters

    • lineIndex: number

      index of line to calculate

    Returns number

  • Private

    Measure a single line given its index. Used to calculate the initial text bounding box. The values are calculated and stored in __lineWidths cache.

    Parameters

    • lineIndex: number

      line number

    Returns number

    Line width

  • Return the object opacity counting also the group property

    Returns number

  • Returns instance's parent EXCLUDING ActiveSelection

    Type Parameters

    • T extends boolean

    Parameters

    • Optional strict: T

      exclude canvas as well

    Returns undefined | TAncestor

  • Returns the coordinates of the object as if it has a different origin

    Parameters

    • originX: TOriginX

      Horizontal origin: 'left', 'center' or 'right'

    • originY: TOriginY

      Vertical origin: 'top', 'center' or 'bottom'

    Returns Point

  • Returns number

    x position according to object's originX property in parent's coordinate plane
    if parent is canvas then this property is identical to getX

  • Returns number

    y position according to object's originY property in parent's coordinate plane
    if parent is canvas then this property is identical to getY

  • Returns height of an object bounding box counting transformations

    Returns number

    height value

    Todo

    shouldn't this account for group transform and return the actual size in canvas coordinate plane?

  • Returns width of an object's bounding box counting transformations

    Returns number

    width value

    Todo

    shouldn't this account for group transform and return the actual size in canvas coordinate plane?

  • Returns index of a character corresponding to where an object was clicked

    Parameters

    Returns number

    Index of a character

  • Gets style of a current selection/cursor (at the start position) if startIndex or endIndex are not provided, selectionStart or selectionEnd will be used.

    Parameters

    • startIndex: number = ...

      Start index to get styles at

    • endIndex: number = ...

      End index to get styles at, if not specified selectionEnd or startIndex + 1

    • Optional complete: boolean

      get full style or not

    Returns Partial<CompleteTextStyleDeclaration>[]

    styles an array with one, zero or more Style objects

  • Return the object scale factor counting also the group scaling, zoom and retina

    Returns Point

    object with scaleX and scaleY properties

  • Parameters

    • e: KeyboardEvent

      Event object

    • isRight: boolean

    Returns number

  • Retrieves the value of property at given character position

    Type Parameters

    • T extends StylePropertiesType

    Parameters

    • lineIndex: number

      the line number

    • charIndex: number

      the character number

    • property: T

      the property name

    Returns IText<Props, SProps, EventSpec>[T]

    the value of 'property'

  • Retrieves viewportTransform from Object's canvas if possible

    Returns TMat2D

    Method

    getViewportTransform

    Member Of

    FabricObject.prototype

  • Override this method to customize grapheme splitting

    Parameters

    • value: string

    Returns string[]

    array of graphemes

    Todo

    the util graphemeSplit needs to be injectable in some way. is more comfortable to inject the correct util rather than having to override text in the middle of the prototype chain

  • Type Parameters

    • T extends "fill" | "stroke"

    Parameters

    • ctx: CanvasRenderingContext2D
    • property: `${T}Style`
    • filler: string | TFiller

    Returns {
        offsetX: number;
        offsetY: number;
    }

    • offsetX: number
    • offsetY: number
  • Type Parameters

    • T extends IText<Props, SProps, EventSpec, T>

    Parameters

    • other: T
    • Optional strict: boolean

      checks only ancestors that are objects (without canvas)

    Returns boolean

  • return true if the object will draw a fill Does not consider text styles. This is just a shortcut used at rendering time We want it to be an approximation and be fast. wrote to avoid extra caching, it has to return true when fill happens, can guess when it will not happen at 100% chance, does not matter if it misses some use case where the fill is invisible.

    Returns null | boolean | ""

    Boolean

    Since

    3.0.0

  • return true if the object will draw a stroke Does not consider text styles. This is just a shortcut used at rendering time We want it to be an approximation and be fast. wrote to avoid extra caching, it has to return true when stroke happens, can guess when it will not happen at 100% chance, does not matter if it misses some use case where the stroke is invisible.

    Returns null | boolean | ""

    Boolean

    Since

    3.0.0

  • Initializes delayed cursor

    Parameters

    • Optional restart: boolean

    Returns void

  • Private

    Initialize text dimensions. Render all text on given context or on a offscreen canvas to get the text width with measureText. Updates this.width and this.height with the proper values. Does not return dimensions.

    Returns void

  • Initializes hidden textarea (needed to bring up keyboard in iOS)

    Returns void

  • Inserts style object for a given line/char index

    Parameters

    • lineIndex: number

      Index of a line

    • charIndex: number

      Index of a char

    • quantity: number

      number Style object to insert, if given

    • Optional copiedStyle: Partial<CompleteTextStyleDeclaration>[]

      array of style objects

    Returns void

  • insert characters at start position, before start position. start equal 1 it means the text get inserted between actual grapheme 0 and 1 if style array is provided, it must be as the same length of text in graphemes if end is provided and is bigger than start, old text is replaced. start/end ar per grapheme position in _text array.

    Parameters

    • text: string

      text to insert

    • style: undefined | Partial<CompleteTextStyleDeclaration>[]

      array of style objects

    • start: number
    • end: number = start

      default to start + 1

    Returns void

  • Inserts style object(s)

    Parameters

    • insertedText: string[]

      Characters at the location where style is inserted

    • start: number

      cursor index for inserting style

    • Optional copiedStyle: Partial<CompleteTextStyleDeclaration>[]

      array of style objects to insert.

    Returns void

  • Handle insertion of more consecutive style lines for when one or more newlines gets added to the text. Since current style needs to be shifted first we shift the current style of the number lines needed, then we add new lines from the last to the first.

    Parameters

    • lineIndex: number

      Index of a line

    • charIndex: number

      Index of a char

    • qty: number

      number of lines to add

    • Optional copiedStyle: {
          [index: number]: TextStyleDeclaration;
      }

      Array of objects styles

    Returns void

  • Checks if object intersects with another object

    Parameters

    • other: ObjectGeometry<ObjectEvents>

      Object to test

    • Optional absolute: boolean = false

      use coordinates without viewportTransform

    • Optional calculate: boolean = false

      use coordinates of current position instead of calculating them

    Returns boolean

    true if object intersects with another object

  • Checks if object intersects with an area formed by 2 points

    Parameters

    • pointTL: Point

      top-left point of area

    • pointBR: Point

      bottom-right point of area

    • Optional absolute: boolean

      use coordinates without viewportTransform

    • Optional calculate: boolean

      use coordinates of current position instead of stored one

    Returns boolean

    true if object intersects with an area formed by 2 points

  • Check if cache is dirty

    Parameters

    • skipCanvas: boolean = false

      skip canvas checks because this object is painted on parent canvas.

    Returns boolean

  • Checks if object is fully contained within area of another object

    Parameters

    • other: ObjectGeometry<ObjectEvents>

      Object to test

    • Optional absolute: boolean = false

      use coordinates without viewportTransform

    • Optional calculate: boolean = false

      use coordinates of current position instead of stored ones

    Returns boolean

    true if object is fully contained within area of another object

  • Checks if object is fully contained within area formed by 2 points

    Parameters

    • pointTL: Point

      top-left point of area

    • pointBR: Point

      bottom-right point of area

    • Optional absolute: boolean

      use coordinates without viewportTransform

    • Optional calculate: boolean

      use coordinates of current position instead of stored one

    Returns boolean

    true if object is fully contained within area formed by 2 points

  • Returns true if the specified control is visible, false otherwise.

    Parameters

    • controlKey: string

      The key of the control. Possible values are usually 'tl', 'tr', 'br', 'bl', 'ml', 'mt', 'mr', 'mb', 'mtr', but since the control api allow for any control name, can be any string.

    Returns boolean

    true if the specified control is visible, false otherwise

  • Returns true if object has no styling or no styling in a line

    Parameters

    • Optional lineIndex: number

      , lineIndex is on wrapped lines.

    Returns boolean

  • Detect if the text line is ended with an hard break text and itext do not have wrapping, return false

    Parameters

    • lineIndex: number

    Returns boolean

  • Type Parameters

    • T extends IText<Props, SProps, EventSpec, T>

    Parameters

    • other: T

      object to compare against

    Returns undefined | boolean

    if objects do not share a common ancestor or they are strictly equal it is impossible to determine which is in front of the other; in such cases the function returns undefined

  • Checks if object is contained within the canvas with current viewportTransform the check is done stopping at first point that appears on screen

    Parameters

    • Optional calculate: boolean = false

      use coordinates of current position instead of .aCoords

    Returns boolean

    true if object is fully or partially contained within canvas

  • Checks if object is partially contained within the canvas with current viewportTransform

    Parameters

    • Optional calculate: boolean

      use coordinates of current position instead of stored ones

    Returns boolean

    true if object is partially contained within canvas

  • Returns true if any of the specified types is identical to the type of an instance

    Parameters

    • Rest ...types: string[]

    Returns boolean

  • measure a text line measuring all characters.

    Parameters

    • lineIndex: number

      line number

    Returns {
        numOfSpaces: number;
        width: number;
    }

    • numOfSpaces: number
    • width: number
  • Detect if a line has a linebreak and so we need to account for it when moving and counting style. It return always 1 for text and Itext. Textbox has its own implementation

    Parameters

    • lineIndex: number
    • Optional skipWrapping: boolean

    Returns 0 | 1

    Number

  • Moves cursor left while keeping selection

    Parameters

    • e: KeyboardEvent

    Returns undefined | boolean

  • Moves cursor left without keeping selection

    Parameters

    • e: KeyboardEvent

    Returns boolean

  • Moves cursor right

    Parameters

    • e: KeyboardEvent

      Event object

    Returns void

  • Moves cursor right while keeping selection

    Parameters

    • e: KeyboardEvent

    Returns undefined | boolean

  • Moves cursor right without keeping selection

    Parameters

    • e: KeyboardEvent

      Event object

    Returns boolean

  • Moves cursor with shift

    Parameters

    • offset: number

    Returns boolean

  • Moves cursor up without shift

    Parameters

    • offset: number

    Returns boolean

  • When set to true, force the object to have its own cache, even if it is inside a group it may be needed when your object behave in a particular way on the cache and always needs its own isolated canvas to render correctly. Created to be overridden since 1.7.12

    Returns boolean

    Boolean

  • unsubscribe an event listener

    Type Parameters

    • K extends string | number | symbol

    Parameters

    • eventName: K

      event name (eg. 'after:render')

    • handler: TEventCallback<any>

      event listener to unsubscribe

    Returns void

  • unsubscribe event listeners

    Parameters

    • handlers: EventRegistryObject<EventSpec>

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

    Returns void

  • unsubscribe all event listeners

    Returns void

  • Observes specified event

    Type Parameters

    • K extends string | number | symbol

    • E

    Parameters

    • eventName: K

      Event name (eg. 'after:render')

    • handler: TEventCallback<E>

      Function that receives a notification when an event of the specified type occurs

    Returns VoidFunction

    disposer

    Alias

    on

  • Parameters

    • handlers: EventRegistryObject<EventSpec>

    Returns VoidFunction

  • Parameters

    • __namedParameters: CompositionEvent

    Returns void

  • override this method to control whether instance should/shouldn't become a drag source,

    Parameters

    • e: DragEvent

    Returns boolean

    should handle event

    See

    also DraggableTextDelegate#isActive

  • Handles onInput event

    Parameters

    • this: IText<Props, SProps, EventSpec> & {
          hiddenTextarea: HTMLTextAreaElement;
      }
    • e: Event

      Event object

    Returns void

  • Handles keydown event only used for arrows and combination of modifier keys.

    Parameters

    • e: KeyboardEvent

      Event object

    Returns void

  • Handles keyup event We handle KeyUp because ie11 and edge have difficulties copy/pasting if a copy/cut event fired, keyup is dismissed

    Parameters

    • e: KeyboardEvent

      Event object

    Returns void

  • This callback function is called every time _discardActiveObject or _setActiveObject try to to select this object. If the function returns true, the process is cancelled

    Parameters

    • Optional options: {
          e?: TPointerEvent;
      }

      options sent from the upper functions

      • Optional e?: TPointerEvent

        event if the process is generated by an event

    Returns boolean

  • Observes specified event once

    Type Parameters

    • K extends string | number | symbol

    • E

    Parameters

    • eventName: K

      Event name (eg. 'after:render')

    • handler: TEventCallback<E>

      Function that receives a notification when an event of the specified type occurs

    Returns VoidFunction

    disposer

    Alias

    once

  • Parameters

    • handlers: EventRegistryObject<EventSpec>

    Returns VoidFunction

  • Removes characters from start/end start/end ar per grapheme position in _text array.

    Parameters

    • start: number
    • end: number = ...

      default to start + 1

    Returns void

  • Remove a style property or properties from all individual character styles in a text object. Deletes the character style object if it contains no other style props. Deletes a line style object if it contains no other character styles.

    Parameters

    • property: StylePropertiesType

    Returns void

  • remove and reflow a style block from start to end.

    Parameters

    • start: number

      linear start position for removal (included in removal)

    • end: number

      linear end position for removal ( excluded from removal )

    Returns void

  • Private

    Parameters

    • ctx: CanvasRenderingContext2D

      Context to render on

    Returns void

  • Parameters

    • Optional options: any

    Returns void

  • Renders cursor

    Parameters

    • ctx: CanvasRenderingContext2D

      transformed context to draw on

    • boundaries: CursorBoundaries

    Returns void

  • Renders cursor on context Top, outside the animation cycle, on request Used for the drag/drop effect. If contextTop is not available, do nothing.

    Parameters

    • selectionStart: number

    Returns void

  • Renders cursor or selection (depending on what exists) it does on the contextTop. If contextTop is not available, do nothing.

    Returns void

  • Renders drag start text selection

    Returns void

  • Parameters

    • e: DragEvent

    Returns void

  • Renders text selection

    Parameters

    • ctx: CanvasRenderingContext2D

      transformed context to draw on

    • boundaries: CursorBoundaries

      Object with left/top/leftOffset/topOffset

    Returns void

  • Sets "angle" of an instance with centered rotation

    Parameters

    • angle: TDegree

      Angle value (in degrees)

    Returns void

  • Scales an object (equally by x and y)

    Parameters

    • value: number

      Scale factor

    Returns void

  • Scales an object to a given height, with respect to bounding box (scaling by x/y equally)

    Parameters

    • value: number

      New height value

    • absolute: boolean = false

      ignore viewport

    Returns void

  • Scales an object to a given width, with respect to bounding box (scaling by x/y equally)

    Parameters

    • value: number

      New width value

    • Optional absolute: boolean

      ignore viewport

    Returns void

  • Finds index corresponding to beginning or end of a word

    Parameters

    • selectionStart: number

      Index of a character

    • direction: 1 | -1

      1 or -1

    Returns number

    Index of the beginning or end of a word

  • Selects a line based on the index

    Parameters

    • selectionStart: number

      Index of a character

    Returns IText<Props, SProps, EventSpec>

  • Selects a word based on the index

    Parameters

    • selectionStart: number

      Index of a character

    Returns void

  • Parameters

    • key: any
    • Optional value: any

    Returns IText<Props, SProps, EventSpec>

  • Sets the visibility of the specified control. please do not use.

    Parameters

    • controlKey: string

      The key of the control. Possible values are 'tl', 'tr', 'br', 'bl', 'ml', 'mt', 'mr', 'mb', 'mtr'. but since the control api allow for any control name, can be any string.

    • visible: boolean

      true to set the specified control visible, false otherwise

    Returns void

    Todo

    discuss this overlap of priority here with the team. Andrea Bogazzi for details

  • Sets the visibility state of object controls, this is just a bulk option for setControlVisible;

    Parameters

    • Optional options: Record<string, boolean> = {}

      with an optional key per control example: {Boolean} [options.bl] true to enable the bottom-left control, false to disable it

    Returns void

  • This callback function is called by the parent group of an object every time a non-delegated property changes on the group. It is passed the key and value as parameters. Not adding in this function's signature to avoid Travis build error about unused variables.

    Returns void

  • Protected

    Sets object's properties from options, for class constructor only. Needs to be overridden for different defaults.

    Parameters

    • Optional options: Record<string, any> = {}

      Options object

    Returns void

  • If text has a path, it will add the extra information needed for path and text calculations

    Returns void

  • Sets the position of the object taking into consideration the object's origin

    Parameters

    • pos: Point

      The new position of the object

    • originX: TOriginX

      Horizontal origin: 'left', 'center' or 'right'

    • originY: TOriginY

      Vertical origin: 'top', 'center' or 'bottom'

    Returns void

  • Parameters

    • value: number

      x position according to object's originX property in parent's coordinate plane
      if parent is canvas then this method is identical to setX

    Returns void

  • As setXY, but in current parent's coordinate plane (the current group if any or the canvas)

    Parameters

    • point: Point

      position according to object's originX originY properties in parent's coordinate plane

    • Optional originX: TOriginX

      Horizontal origin: 'left', 'center' or 'right'

    • Optional originY: TOriginY

      Vertical origin: 'top', 'center' or 'bottom'

    Returns void

  • Parameters

    • value: number

      y position according to object's originY property in parent's coordinate plane
      if parent is canvas then this property is identical to setY

    Returns void

  • Sets selection end (right boundary of a selection)

    Parameters

    • index: number

      Index to set selection end to

    Returns void

  • Sets selection start (left boundary of a selection)

    Parameters

    • index: number

      Index to set selection start to

    Returns void

  • Set the selectionStart and selectionEnd according to the new position of cursor mimic the key - mouse navigation when shift is pressed.

    Parameters

    • start: number
    • end: number
    • newSelection: number

    Returns void

  • Sets style of a current selection, if no selection exist, do not set anything.

    Parameters

    • Optional styles: object

      Styles object

    • Optional startIndex: number = ...

      Start index to get styles at

    • Optional endIndex: number = ...

      End index to get styles at, if not specified selectionEnd or startIndex + 1

    Returns void

  • Turns the character into an 'inferior figure' (i.e. 'subscript')

    Parameters

    • start: number

      selection start

    • end: number

      selection end

    Returns void

  • Turns the character into a 'superior figure' (i.e. 'superscript')

    Parameters

    • start: number

      selection start

    • end: number

      selection end

    Returns void

  • Set an object position to a particular point, the point is intended in absolute ( canvas ) coordinate. You can specify originX and originY values, that otherwise are the object's current values.

    Parameters

    • point: Point

      position in canvas coordinate plane

    • Optional originX: TOriginX

      Horizontal origin: 'left', 'center' or 'right'

    • Optional originY: TOriginY

      Vertical origin: 'top', 'center' or 'bottom'

    Returns void

    Example

    Set object's bottom left corner to point (5,5) on canvas

    object.setXY(new Point(5, 5), 'left', 'bottom').
    
  • Shifts line styles up or down

    Parameters

    • lineIndex: number

      Index of a line

    • offset: number

      Can any number?

    Returns void

  • Decide if the object should cache or not. Create its own cache level objectCaching is a global flag, wins over everything needsItsOwnCache should be used when the object drawing method requires a cache step. None of the fabric classes requires it. Generally you do not cache objects in groups because the group outside is cached. Read as: cache if is needed, or if the feature is enabled but we are not already caching.

    Returns boolean

  • override this function in order to customize the drawing of the control box, e.g. rounded corners, different border style.

    Parameters

    • ctx: CanvasRenderingContext2D

      ctx is rotated and translated so that (0,0) is at object's center

    • size: Point

      the control box size used

    Returns void

  • Returns true if object has a style property or has it ina specified line This function is used to detect if a text will use a particular property or not.

    Parameters

    • property: StylePropertiesType

      to check for

    • Optional lineIndex: number

      to check the style on

    Returns boolean

  • block cursor/selection logic while rendering the exported canvas

    Parameters

    • Optional options: any

    Returns HTMLCanvasElement

    Todo

    this workaround should be replaced with a more robust solution

  • Converts an object into a data-url-like string

    Parameters

    • options: any = {}

      Options object

    Returns string

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

  • Returns (dataless) object representation of an instance

    Parameters

    • Optional propertiesToInclude: any[]

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

    Returns any

    Object representation of an instance

  • Returns a JSON representation of an instance

    Returns any

    JSON

  • Returns object representation of an instance

    Type Parameters

    • T extends Omit<Props & TClassProperties<IText<Props, SProps, EventSpec>>, keyof SProps>

    • K extends string | number | symbol = never

    Parameters

    • Optional propertiesToInclude: K[] = []

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

    Returns Pick<T, K> & SProps

    Object representation of an instance

  • Returns string representation of an instance

    Returns string

    String representation of text object

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

    Parameters

    • property: string

      Property to toggle

    Returns IText<Props, SProps, EventSpec>

  • Transforms context when rendering an object

    Parameters

    • ctx: CanvasRenderingContext2D

      Context

    Returns void

  • Parameters

    • skipGroup: boolean = false

    Returns string

  • Translates the coordinates from origin to center coordinates (based on the object's dimensions)

    Parameters

    • point: Point

      The point which corresponds to the originX and originY params

    • originX: TOriginX

      Horizontal origin: 'left', 'center' or 'right'

    • originY: TOriginY

      Vertical origin: 'top', 'center' or 'bottom'

    Returns Point

  • Translates the coordinates from a set of origin to another (based on the object's dimensions)

    Parameters

    • point: Point

      The point which corresponds to the originX and originY params

    • fromOriginX: TOriginX

      Horizontal origin: 'left', 'center' or 'right'

    • fromOriginY: TOriginY

      Vertical origin: 'top', 'center' or 'bottom'

    • toOriginX: TOriginX

      Horizontal origin: 'left', 'center' or 'right'

    • toOriginY: TOriginY

      Vertical origin: 'top', 'center' or 'bottom'

    Returns Point

  • Translates the coordinates from center to origin coordinates (based on the object's dimensions)

    Parameters

    • center: Point

      The point which corresponds to center of the object

    • originX: TOriginX

      Horizontal origin: 'left', 'center' or 'right'

    • originY: TOriginY

      Vertical origin: 'top', 'center' or 'bottom'

    Returns Point

  • Check if this object or a child object will cast a shadow used by Group.shouldCache to know if child has a shadow recursively

    Returns boolean

    Deprecated

  • Type Parameters

    Parameters

    • object: Record<string, unknown>
    • __namedParameters: Abortable & {
          extraParam?: string;
      } = {}

    Returns Promise<S>

  • Returns FabricText instance from an SVG element (not yet implemented)

    Parameters

    • element: HTMLElement

      Element to parse

    • Optional options: Abortable

      Options object

    • Optional cssRules: CSSRules

    Returns Promise<FabricText<{
        fontSize: number;
        left: number;
        linethrough: boolean;
        overline: boolean;
        signal?: AbortSignal;
        strokeWidth: number;
        top: number;
        underline: boolean;
    }, SerializedTextProps, ObjectEvents>>

    Static

    Member Of

    Text

Generated using TypeDoc