Class StaticCanvas<EventSpec>

Static canvas class

See

demo

Fires

before:render

Fires

after:render

Fires

canvas:cleared

Fires

object:added

Fires

object:removed

Type Parameters

Hierarchy

Implements

Constructors

Properties

Accessors

Methods

Constructors

Properties

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

Type declaration

    • (): void
    • Returns void

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

        • Optional reason: any

        Returns void

TODO

needs to end up in the constructor too

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

Type declaration

  • left: number
  • top: number
allowTouchScrolling: boolean

Todo

move to Canvas

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


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

controlsAboveOverlay: boolean

Todo

move to Canvas

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.

enableRetinaScaling: boolean

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

Default


hasLostContext: boolean
height: number

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

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


nextRenderHandle: number
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


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


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


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: TOptions<StaticCanvasOptions> = staticCanvasDefaults

Accessors

  • 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

  • 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

  • Parameters

    • key: string
    • value: any

    Returns void

  • 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

  • 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

  • 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

  • Returns true if collection contains an object.
    Prefer using FabricObject#isDescendantOf for performance reasons instead of a.contains(b) use b.isDescendantOf(a)

    Parameters

    Returns boolean

    true if collection contains an object

  • 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

  • Private

    Clears the canvas element, disposes objects and frees resources.

    Invoked as part of the async operation of dispose.

    CAUTION:

    This method is UNSAFE. You may encounter a race condition using it if there's a requested render. Call this method only if you are sure rendering has settled. Consider using dispose as it is SAFE

    Returns void

  • 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

  • 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 true if collection contains no objects

    Returns boolean

    true if collection is empty

  • 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<StaticCanvas<EventSpec>>

    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

  • 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

  • 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

  • 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 StaticCanvas<EventSpec>

  • 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

  • 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 StaticCanvas<EventSpec>

  • 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