iDraw.js Documentation

repository·main·Indexed 19 days ago

https://github.com/idrawjs/idraw

A JavaScript framework for web-based drawing that provides an abstraction for creating and managing drawing materials within a canvas-like environment. It includes a rendering engine via @idraw/renderer, a core engine for managing drawing surfaces through the Board and Core classes, and a middleware architecture for extending functionality with tools for interaction, navigation, and element creation.

Tokens
55.5K
Snippets
211
Records
243
Agent score
78%

What's inside iDraw.js

  1. Quick Start with @idraw/renderer

    main

    To use the renderer, instantiate a new Renderer with a configuration object, then call the .render() method passing a canvas element and an array of elements to draw.

    Configuration Options:

    • width: The width of the rendering area.
    • height: The height of the rendering area.
    • contextWidth: The width of the drawing context.
    • contextHeight: The height of the drawing context.
    • devicePixelRatio: The pixel ratio for high-DPI displays.
    import Renderer from '@idraw/renderer';
    
    const renderer = new Renderer({
      width: 600,
      height: 400,
      contextWidth: 600,
      contextHeight: 400,
      devicePixelRatio: 1,
    });
    
    const canvas = document.querySelector('canvas');
    renderer.render(canvas, {
      elements: [
        {
          name: "rect-001",
          x: 10,
          y: 10,
          w: 200,
          h: 100,
          type: "rect",
          detail: {
            bgColor: "#f0f0f0",
            borderRadius: 20,
            borderWidth: 10,
            borderColor: "#bd0b64",
          },
        },
      ]
    });
  2. Get started with iDraw (Vanilla JS)

    main

    To use iDraw in a standard JavaScript environment, import the iDraw class, instantiate it by passing a DOM element and an options object, and then use methods like addMaterial to draw shapes.

    Supported options in the constructor include:

    • width: The width of the drawing area.
    • height: The height of the drawing area.
    • devicePixelRatio: The pixel ratio for high-DPI displays.
    import { iDraw } from 'idraw';
    
    const idraw = new iDraw(
      document.querySelector('#app'),
      {
        width: 600,
        height: 400,
        devicePixelRatio: 1,
      }
    );
    
    idraw.addMaterial({
      name: "rect-1",
      type: "rect",
      x: 140,
      y: 120,
      width: 200,
      height: 100,
      fill: "#f7d3c1",
      strokeWidth: 4,
      stroke: "#ff6032",
      cornerRadius: 20,
    });
  3. Import core iDraw components and utilities

    main

    The idraw package serves as a central entrypoint for the entire library. It re-exports essential classes, middleware, utilities, and types from sub-packages like @idraw/core, @idraw/renderer, and @idraw/util.

    Key categories of exports include:

    • Core Engine: Core, Board, Sharer, Calculator, and iDraw.
    • Middleware: A suite of specialized middleware for handling interactions such as MiddlewareScroller, MiddlewareScaler, MiddlewareDragger, MiddlewareTextEditor, and MiddlewareRuler.
    • Renderer: The Renderer class for drawing operations.
    • Utilities: A vast collection of helper functions for color manipulation (toColorHexStr), geometry (calcDistance), asset management (createAssetId), and SVG/HTML processing (svgToMaterial, parseSVGPath).
    • Events: eventKeys and types for handling IDrawEvent.
  4. MiddlewarePathCreator lifecycle and events

    main

    The MiddlewarePathCreator implements the Middleware interface and manages its lifecycle through the following hooks and event listeners:

    Lifecycle Hooks

    • use(): Initializes styles, attaches event listeners for PATH_CREATE and CLEAR_PATH_CREATE, and mounts the root DOM element.
    • disuse(): Cleans up styles, removes event listeners, clears current path data, and destroys the root DOM element.
    • beforeDrawFrame(): Updates the visual style of anchor elements before the viewer renders a frame.
    • hover(): Triggers a CURSOR event with type 'pen' when the mouse hovers over the active area.

    Core Events Handled

    • coreEventKeys.PATH_CREATE: Triggers pathCreateCallback to start the drawing mode.
    • coreEventKeys.CLEAR_PATH_CREATE: Triggers clearPathCreateCallback to refine the current path and exit drawing mode.
    • coreEventKeys.CURSOR: Dispatched by the middleware to signal the 'pen' cursor type.
  5. Configure Gradient Colors

    main

    Gradients are supported via LinearGradientColor and RadialGradientColor types, which can be assigned to fill or stroke properties.

    Linear Gradient: Requires a start point, an end point, and an array of GradientStop objects.

    Radial Gradient: Requires an inner GadialCircle (point + radius) and an outer GadialCircle.

    Both support an optional angle and a transform array of TransformAction objects.

    const linearGradient: LinearGradientColor = {
      type: 'linear-gradient',
      start: { x: 0, y: 0 },
      end: { x: 100, y: 100 },
      stops: [
        { offset: 0, color: '#ff0000' },
        { offset: 1, color: '#0000ff' }
      ]
    };
  6. Understand the structure of FlattenMaterial and FlattenLayout

    main

    In idraw, FlattenMaterial and FlattenLayout are used to represent the state of a material or layout in a flattened key-value format. This is useful for tracking changes (before/after) in undo/redo systems. Instead of a nested object, properties are represented using dot notation for attributes and bracket notation for array indices.

    Example of a flattened object:

    {
        "x": 0,
        "y": 0,
        "w": 0,
        "h": 0,
        "attributes.color": "#FFFFFF",
        "attributes.strokeWidth[0]": 10,
        "attributes.strokeWidth[1]": 20
    }
    export type FlattenMaterial = Record<string, string | number | undefined | null>;
    export type FlattenLayout = Record<string, string | number | undefined | null>;
  7. Understand CoreEventMap and available event types

    main

    The CoreEventMap is the central event registry for the idraw engine. It extends BoardBaseEventMap and provides hooks for various engine states and user interactions. Developers can listen to these events to implement custom logic or middleware.

    Core Event Categories:

    Basic State Events

    • cursor: Emitted when the cursor type changes (e.g., resize-left, drag-active, default).
    • change: Emitted when data is modified (includes setData, updatingMaterial, etc.).
    • changing: Emitted during the transition of a change.
    • ruler: Provides state for show and showGrid.
    • scale: Provides the current scale value.
    • modeChange: Emitted when the IDrawMode changes.

    Middleware & Interaction Events

    • create: Used for material creation middleware. Supports all MaterialType except 'path', 'foreignObject', or 'svgCode'.
    • select: Handles selection logic including clickCanvas, selectMaterial, and selectMaterialsByPositions.
    • contextMenu: Provides the pointerContainer and selectedMaterials for custom right-click menus.
    • textEdit / textChange: Handles text-specific editing and attribute updates.
    • pathEdit / pathCreate: Handles path-specific creation and editing workflows.
    • snapToGrid: Provides enable state for grid snapping.
  8. Use iDraw middleware for interaction handling

    main

    iDraw uses a middleware system to extend the functionality of the board and core engine. You can import specific middleware classes to handle user interactions like scrolling, scaling, or dragging. Common middleware available through the main entrypoint include:

    • MiddlewareScroller: Handles view scrolling.
    • MiddlewareScaler: Handles zooming/scaling.
    • MiddlewareDragger: Handles object dragging.
    • MiddlewarePointer: Handles pointer/mouse interactions.
    • MiddlewareTextEditor: Handles text editing within the canvas.
    • MiddlewareRuler: Provides measurement tools.
    • MiddlewarePathCreator / MiddlewarePathEditor: For path-based drawing and editing.
    • MiddlewareLayoutSelector / MiddlewareSelector: For selecting elements and managing layouts.
  9. Understand the MaterialBase structure

    main

    The MaterialBase type is the foundation for all materials in idraw. It contains common properties used for positioning, transformation, and visual styling.

    Core Properties:

    • id: Unique identifier.
    • name: Optional display name.
    • x, y, width, height: Spatial dimensions.
    • angle: Portable rotation attribute.
    • transform: Can be a MaterialTransform object (containing rotate, translate, skew, scale, or matrix) or a MaterialTransformMatrix (a 6-element array).

    Visual Attributes:

    • opacity: Number value.
    • fill / stroke: Can be a MaterialColor (string, LinearGradientColor, or RadialGradientColor).
    • fillOpacity / strokeOpacity: Number values.
    • cornerRadius: Number or [top-left, top-right, bottom-left, bottom-right] array.
    • shadowColor, shadowOffsetX, shadowOffsetY, shadowBlur: Shadow styling.

    Layout & Display:

    • display: 'inline' | 'block' | 'none' | 'inline-block'.
    • visibility: 'visible' | 'hidden' | 'collapse'.
    • overflow: 'visible' | 'hidden'.
  10. How iDraw modes and middlewares work together

    main

    iDraw manages user interaction through a combination of Modes and Middlewares.

    1. Modes: A mode (like create or drag) defines a high-level state of the application. Changing a mode sets specific boolean flags in the store (e.g., enableCreate, enableDrag).
    2. Middlewares: These are functional layers that handle specific tasks like scrolling, scaling, or selecting.
    3. The Connection: When a mode changes, the runMiddlewares function is called. It reads the enabled flags from the store and uses core.use() to attach the corresponding middlewares (like MiddlewareScroller or MiddlewareDragger) or core.disuse() to remove them.

    For example, switching to drag mode enables the MiddlewareDragger while disabling MiddlewareCreator.