LeaferJS

repository·main·Indexed 23 days ago

https://github.com/leaferjs/leafer-ui

A high-performance Canvas engine designed for large-scale graphics, interactive editors, and infinite canvas applications. It supports up to 1 million interactive elements with high frame rates and provides Figma-level editing capabilities. The library includes a core engine, an App class for layer management (ground, tree, sky), and various UI elements such as Rect, Ellipse, Group, Box, and Canvas.

Tokens
23.5K
Snippets
18
Records
213
Agent score
87%

What's inside leafer-ui

  1. Install leafer-ui

    main

    Install the main leafer-ui package to start using the Canvas engine. If you plan to use plugins, it is highly recommended to install the cross-platform core packages simultaneously to prevent version mismatch issues.

    npm install leafer-ui
    
    # Recommended if using plugins to ensure version synchronization
    npm install leafer-ui @leafer-ui/core @leafer-ui/draw
  2. Install LeaferJS

    main

    You can install the main leafer-ui package via npm.

    Important: When using plugins, it is highly recommended to install the core packages together to prevent version mismatch issues.

    npm install leafer-ui
    
    # Recommended: Install core packages together when using plugins
    npm install leafer-ui @leafer-ui/core @leafer-ui/draw
  3. Quick start with LeaferJS

    main

    To create a basic interactive application, import Leafer and a shape (like Rect) from leafer-ui. Initialize the Leafer instance by passing a view (e.g., window), create your shapes with properties like draggable: true, and add them to the leafer instance using .add().

    import { Leafer, Rect } from 'leafer-ui'
    
    // Create an adaptive window interactive application
    const leafer = new Leafer({ view: window })
    
    // Create a draggable rectangle
    const rect = new Rect({
      x: 100,
      y: 100,
      width: 200,
      height: 200,
      fill: '#32cd79',
      draggable: true,
    })
    
    leafer.add(rect)
  4. Use the UI class for UI elements

    main

    The UI class is the base class for all UI elements in LeaferJS. It extends Leaf and provides a comprehensive set of properties for positioning, sizing, styling, effects, and interaction. You can create UI elements using the UI.one() static method by passing an input data object.

    Key capabilities include:

    • Transformations: Position (x, y), size (width, height), scale (scaleX, scaleY), rotation, and skew.
    • Styling: Fill, stroke, corner radius, and dash patterns.
    • Effects: Shadows, blurs, grayscale, and filters.
    • Interactions: Draggable, hittable, and cursor management.
    • Layout: Support for flow layouts, padding, and gaps.
    • Animations: Support for keyframes and transitions via the animate() method.
  5. Initialize LeaferUI modules via the partner module

    main
    The partner module acts as a bridge to automatically extend core drawing types with specialized modules. By importing this module, you augment the base classes from @leafer-ui/draw with additional capabilities for text conversion, color conversion, painting (images and gradients), and effects. This is useful for ensuring all necessary modules are correctly assigned to their respective base classes.
  6. Initialize a Leafer instance

    main

    The Leafer class is the root container for a scene. You can initialize it by passing a userConfig object (of type ILeaferConfig) and optional initial data. The instance manages the canvas, renderer, watcher, and interaction layers.

    Common configuration options include:

    • start: boolean (default true) - whether to start the engine immediately.
    • hittable: boolean (default true) - whether the canvas supports interaction.
    • smooth: boolean (default true) - enables smooth rendering.
    • width / height: number - sets the initial canvas dimensions.
    • type: ILeaferType - defines the Leafer type (used by viewport plugins).
  7. Configure Interaction behavior via IInteractionConfig

    main

    The InteractionBase class uses an IInteractionConfig object to control interaction parameters. You can pass a userConfig during construction to override default settings.

    Key configuration sub-objects:

    • move: Controls dragging and movement behavior (accessed via .m).
    • pointer: Controls pointer-specific settings like hitRadius, dragDistance, tapTime, and longPressTime (accessed via .p).
    • keyEvent: A boolean to enable/disable keyboard event processing.
  8. Configure the IEditor via IEditorConfig

    main

    The IEditorConfig object allows you to customize the behavior and appearance of the editor. Key configuration areas include:

    • Visuals: Customize stroke, strokeWidth, spread (gap between edit box and element), and pointFill (for control points).
    • Control Points: Define point, middlePoint, resizeLine, and linkPoint using IEditPointInputData.
    • Selection & Interaction:
      • selector: Configure hover, select (e.g., 'press' or 'tap'), and multipleSelect.
      • boxSelect: Set to 'hit' or 'includes' for box selection.
      • moveable, resizeable, rotateable, skewable: Enable/disable specific transformations (can be set to 'gesture' or specific modes like 'zoom' or 'rotate').
    • Transformation Behavior:
      • around / rotateAround: Set the center point for scaling/rotation.
      • lockRatio: Boolean or 'corner' to lock aspect ratio.
      • arrowStep / arrowFastStep: Control movement increments when using arrow keys.
    • Masking: Use mask with dimOthers (to dim non-selected items) or bright (to highlight only the selected item).
  9. Configure Canvas properties

    main

    When instantiating or updating a Canvas, you can use the following configuration options:

    PropertyTypeDescription
    widthINumberThe width of the canvas surface.
    heightINumberThe height of the canvas surface.
    pixelRatioINumberThe device pixel ratio for high-DPI support.
    smoothbooleanWhether to enable image smoothing.
    safeResizebooleanIf true, uses a safer resizing method to prevent artifacts.
    contextSettingsICanvasContext2DSettingsSettings applied to the underlying CanvasContext2D.
    urlstringA temporary base64 string used to load canvas data via drawImage.
  10. Configure interaction settings via IInteractionConfig

    main

    The IInteractionConfig interface defines the global configuration for user interactions (wheel, pointer, touch, etc.) within LeaferJS. You can customize how the engine responds to mouse wheels, pointer events, and touch gestures.

    // Example of the structure for IInteractionConfig
    const interactionConfig: IInteractionConfig = {
        wheel: {
            zoomSpeed: 0.5,
            moveSpeed: 0.5,
            rotateSpeed: 0.5,
            delta: { x: 20, y: 8.0 },
        },
        pointer: {
            type: 'pointer',
            snap: true,
            hitRadius: 5,
            tapTime: 120,
            longPressTime: 800,
            transformTime: 500,
            hover: true,
            dragHover: true,
            dragDistance: 2,
            swipeDistance: 20,
        },
        touch: {
            preventDefault: 'auto'
        },
        multiTouch: {},
        move: { autoDistance: 2 },
        zoom: {},
        cursor: true,
        keyEvent: true
    };
  11. Configure the App with IAppConfig

    main

    When initializing an application, you can provide an IAppConfig object to configure various layers of the engine. The configuration extends ILeaferConfig and includes specific keys for managing the background layers and the editor:

    • ground: Configuration for the ground layer.
    • tree: Configuration for the tree layer.
    • sky: Configuration for the sky layer.
    • editor: Configuration for the editor (using IEditorConfig).