Fabric.js

repository·master·Indexed 12 days ago

https://github.com/fabricjs/fabric.js

A powerful JavaScript HTML5 canvas library providing an object model for canvas and an SVG-to-canvas parser. Version 7.4.0 supports both browser and Node.js environments, offering built-in shapes, animations, image filters, and a flexible Layout Manager with FitContent, Fixed, and Clippath strategies. The ecosystem includes specialized extensions for aligning guidelines, cropping controls, and serialized data migration helpers.

Tokens
25K
Snippets
88
Records
117
Agent score
98%

What's inside Fabric.js

  1. Use @fabricjs/data-updaters for serialized data migration

    master
    @fabricjs/data-updaters is a package of serialized data migration helpers for Fabric.js. It provides updater helpers designed to migrate older serialized Fabric.js data formats to newer, compatible versions, ensuring backward compatibility when loading legacy JSON representations of canvas objects.
  2. Use @fabricjs/gradient-controls for linear gradient helpers

    master

    The @fabricjs/gradient-controls package provides helper functions to manage and manipulate linear gradient controls within Fabric.js. It exposes the createLinearGradientControls function, which allows you to implement interactive gradient controls. This package is a standalone module that requires @fabricjs/core as a dependency.

    import { createLinearGradientControls } from '@fabricjs/gradient-controls';
  3. Compare FitContent vs Fixed vs Clippath layout strategies

    master

    When working with groups in Fabric.js, choosing the right layout strategy is critical for how the group responds to content changes:

    StrategyBehavior on Add/RemoveDimension Control
    FitContentGroup size and center update to fit the new bounding box.Automatic (based on content).
    FixedGroup size remains constant; content is cropped by the fixed box.Manual (developer sets width or height).
    ClippathGroup size and center are driven by the clipPath object.Dependent on clipPath.

    Note on Fixed Layout: The Fixed strategy is the only one where you can change the group's width and height at will without them being reset during the next performLayout call.

  4. How the Layout Manager works

    master

    The Layout Manager is responsible for calculating the size and position of a group based on its member objects. It provides a structured lifecycle for layout operations to ensure objects are correctly repositioned relative to the group center and that the group's bounding box is updated.

    Layout Lifecycle

    Every performLayout call follows this execution flow:

    1. onBeforeLayout: Subscribes to object events and fires a user event.
    2. getLayoutResult: Calculates the new layout using a strategy (e.g., FitContent).
    3. commitLayout: Applies the calculated width, height, and position (top/left) to the group.
    4. onAfterLayout: Fires a completion event and bubbles the layout operation to parent groups.

    Layout Strategies

    You can choose different strategies to define how a group behaves when its contents change:

    • FitContent strategy: The classic behavior. The group's size and center are determined by the bounding box of all contained objects. When objects are added or removed, the group grows or shrinks, and objects are offset to maintain their relative positions around the new center.
    • Fixed layout strategy: Allows you to specify a fixed width or height. Once initialized, adding or removing objects will not change the group's dimensions or position. The group acts as a fixed container that crops its contents.
    • Clippath layout strategy: The group's size and center are tied to a clipPath rather than the objects themselves. The group is as large as the clipPath and centered on it.
  5. Understand FabricJS extensions and plugins

    master

    FabricJS extensions and plugins are features that exist outside the core library to prevent scope creep. While the core library focuses on rendering, interactive layers, and serialization, extensions provide specialized functionality such as:

    • Niche Filters: Image filters with specific or uncommon use cases.
    • High-level Interactions: Complex UX behaviors like guidelines or snapping.
    • UX-focused Objects: High-level objects designed specifically for user experience.
    • Pre-built Control Sets: Reference implementations of control sets that can be built using the core API but are provided ready-to-use.

    Extensions are not included in the main FabricJS bundle. They are available as separate ES modules or extension bundles.

  6. How to use @fabricjs/core

    master

    The @fabricjs/core package is the environment-neutral shared runtime for Fabric.js. It is used internally by @fabricjs/browser and @fabricjs/node.

    Important Usage Guidelines:

    • Preferred Entrypoints: Most applications should not import @fabricjs/core directly. Instead, use @fabricjs/browser for browser-based applications or @fabricjs/node for Node.js applications.
    • Direct Import Warning: If you choose to import @fabricjs/core directly for an advanced integration, be aware that it is not a DOM-free API. You must provide a suitable environment implementation if your code touches the DOM or the canvas.
    • Version Consistency: Ensure that @fabricjs/core is kept on the same version as all other @fabricjs/* packages and the legacy fabric facade in your application to prevent compatibility issues.
  7. Handle data versioning when using Origin Wrapper Updater

    master

    Fabric.js data exports include a version tag representing the library version used during export. To prevent incorrect positioning when loading old data, you should implement a conditional update strategy:

    1. Check the version property on the loaded data/label during session instantiation.
    2. If the version indicates the data needs an update (i.e., it was exported with different origin defaults), call installOriginWrapperUpdater() for that specific session.
    3. Do not make this a fixed execution for all sessions; only run it when the data version requires it.
  8. Understand group object removal behavior

    master

    When removing an object from a group using group.remove(A), the following occurs:

    1. The object A is removed from the group structure.
    2. To prevent visual jumping, the transform state of object A absorbs the transform state of the group. This ensures that if the object is added back to the scene (outside the group), its visual position and appearance remain unchanged.
  9. Understand Fabric.js package structure and migration

    master

    Fabric.js has moved to a modular architecture. Understanding the roles of different packages is crucial for correct installation and importing.

    PackageRole
    fabricLegacy compatibility facade. Re-exports @fabricjs/browser.
    @fabricjs/browserPreferred entrypoint for new browser applications.
    @fabricjs/nodePreferred entrypoint for new Node.js applications. Owns Node-specific dependencies.
    @fabricjs/coreShared, environment-neutral runtime. Intended for advanced/shared dependencies.
    Extension packagesOptional features (e.g., @fabricjs/aligning-guidelines).

    Important Migration Rules

    • Matching Versions: Keep fabric and every @fabricjs/* package on matching versions. Mixing mismatched versions can load separate runtimes.
    • Preferred Imports: New applications should use explicit entrypoints:
      • import { Canvas } from '@fabricjs/browser';
      • import { StaticCanvas } from '@fabricjs/node';
      • import { AligningGuidelines } from '@fabricjs/aligning-guidelines';
    • Core Usage: @fabricjs/core is environment-neutral but is not a DOM-free API. If you use core APIs that touch the DOM or canvas, you must provide a suitable environment implementation.