Pikaso HTML5 Canvas Library

repository·master·Indexed 42 days ago

https://github.com/pikasojs/pikaso

A seamless, fully-typed, and fully-tested HTML5 Canvas library built on top of Konva. Pikaso provides high-level features for interactive canvas applications, including state management (Undo/Redo/Reset), JSON import/export, free-style drawing, advanced selection and transformation tools, and specialized cropping tools (Fixed/Flexible, Circular/Rectangular). It supports browser environments, React via an official hook, and Node.js.

Tokens
25.1K
Snippets
106
Records
126
Agent score
53%

What's inside Pikaso

  1. Pikaso core features overview

    master

    Pikaso is a high-level HTML5 Canvas library built on top of Konva. It provides advanced features including:

    • Drawing & Shapes: Shape and FreeStyle drawing, built-in shapes, customizable shapes, and groups.
    • Transformation: Rotation, transformation, flipping, and interactive selection management.
    • Editing: Interactive text editing, customizable cropping, and snap to grid.
    • State & Data: State management (Undo/Redo/Reset), JSON Import/Export, and event management.
    • Media & Effects: Image and SVG support, background image/overlay management, and filter management (including custom filters).
    • Export: Export to PNG and JPEG.
  2. Compare Pikaso and Konva

    master
    Pikaso is built on top of Konva. While Konva provides the foundation for shapes, dragging, styling, and events on the HTML5 Canvas, Pikaso adds a layer of simplicity and advanced features like state management (Undo/Redo), JSON import/export, free-style drawing, and advanced selection/transformation tools.
  3. Install Pikaso

    master

    You can install Pikaso using NPM, Yarn, or by including it via a <script> tag for UMD loading.

    # Using NPM
    npm install pikaso --save
    
    # Using Yarn
    yarn add pikaso
    <!-- Using <script> tag (UMD) -->
    <script src="https://cdn.jsdelivr.net/npm/pikaso@latest/umd/pikaso.min.js" type="text/javascript" />
  4. Get started with Pikaso

    master

    To initialize a new Pikaso editor, import the Pikaso class and instantiate it by providing a container element (an HTML element where the canvas will be rendered).

    import Pikaso from 'pikaso'
    
    const editor = new Pikaso({
      container: document.getElementById('<YOUR_DIV_ID>'),
    })
  5. Manage canvas backgrounds with the Background class

    master

    The Background class manages the background layer of a Pikaso Board. It consists of two main components: an image (an ImageModel) and an overlay (a RectModel). The overlay can be used to apply a color tint or mask over the background image.

    Key capabilities:

    • Loading images from a File object or a URL.
    • Controlling how the image fits the stage using different sizing strategies.
    • Applying color fills to the background overlay.
    • Accessing the underlying Konva nodes via the nodes getter.
    • Retrieving the current background position via getPosition().
    import { Background } from 'pikaso'
    
    // Assuming 'board' is an existing instance of Board
    const background = new Background(board);
    
    // Set an image from a URL with a specific sizing strategy
    await background.setImageFromUrl('https://example.com/image.jpg', { size: 'cover' });
    
    // Apply a color overlay
    background.fill('#ff0000');
    
    // Get the position
    const pos = background.getPosition(); // { x, y }
  6. Manage shape selection with the Selection class

    master

    The Selection class is responsible for managing which shapes are currently selected on the Board. It handles multi-selection via click/drag, provides a visual transformer (via Konva) for resizing and rotating, and manages selection-related events.

    Key capabilities include:

    • Multi-selection: Select multiple shapes using a drag-to-select zone or by holding Shift (add) or Ctrl (toggle) while clicking.
    • Visual Feedback: Automatically manages a Konva.Transformer to show handles for selected shapes.
    • Keyboard Control: Supports moving selected shapes and deleting them via configurable keyboard mappings.
    • Selection Zone: Implements a rectangular drag-to-select area on the board background.
    import { Selection } from 'pikaso';
    
    // Assuming 'board' is an instance of Board
    const selection = new Selection(board);
    
    // Access selected shapes
    const selectedShapes = selection.shapes;
    
    // Check if selection is active
    if (selection.isVisible) {
      // ...
    }
  7. Initialize the Pikaso editor

    master

    To use Pikaso, instantiate the Pikaso class by passing a Settings object. In a browser environment, you must provide a container element (an HTMLDivElement) where the editor will be rendered. You can optionally provide a registerShapes function to extend the default set of shapes.

    const editor = new Pikaso({
      container: document.getElementById('myDiv') as HTMLDivElement
    })
  8. Draw text shapes with TextDrawer

    master

    The TextDrawer class is used to create and manage text shapes on a Pikaso Board. It extends ShapeDrawer and utilizes Konva.Text under the hood.

    To use it, you typically interact with the insert method to add a new text shape to the board using a configuration object compatible with Konva.TextConfig. The drawer manages the lifecycle of the text shape, including its creation and drawing state.

    // Assuming 'board' is an existing instance of Board
    const textDrawer = new TextDrawer(board);
    
    // Insert a new text shape using Konva.TextConfig properties
    const textModel = textDrawer.insert({
      text: 'Hello Pikaso!',
      fontSize: 20,
      fill: 'black',
      x: 100,
      y: 100
    });
  9. Select and manipulate shapes using Selection API

    master

    The Selection class provides several methods to programmatically control shape selection and manipulation:

    Selection Methods

    • find(selector: (shape: ShapeModel) => boolean): Selects shapes that match the provided predicate.
    • selectAll(): Selects all active shapes on the board.
    • deselectAll(): Clears all current selections.
    • reselect(): Re-applies the current selection (useful after state changes).
    • add(shape: ShapeModel): Adds a specific shape to the current selection.
    • toggle(shape: ShapeModel): Toggles a shape's selected state.
    • deselect(shape: ShapeModel): Removes a specific shape from the selection.
    • multi(shapes: ShapeModel[]): Sets the selection to exactly the provided array of shapes.

    Manipulation Methods

    • delete(): Deletes all currently selected shapes and creates an undo/redo history entry.
    • moveX(value: number): Moves selected shapes horizontally by the specified value (returns a Promise).
    • moveY(value: number): Moves selected shapes vertically by the specified value (returns a Promise).
    • group(groupName: string): Groups the selected shapes under a specific name.
    • addFilter(filters: Filters | Filters[]): Applies visual filters to the selected shapes.
    • removeFilter(filters: FilterFunctions | FilterFunctions[]): Removes filters from the selected shapes.
    // Find and select all rectangles
    selection.find(shape => shape.node.getType() === 'Rect');
    
    // Select all
    selection.selectAll();
    
    // Move selected shapes right by 10 units
    await selection.moveX(10);
    
    // Delete selection
    selection.delete();
    
    // Group selection
    selection.group('my-group');
  10. Convert a File to a Data URL with imageToDataUrl

    master

    Use the imageToDataUrl function to asynchronously convert a browser File object (such as an image uploaded via an <input type="file">) into a base64-encoded Data URL string. This is useful for generating instant previews of images before they are uploaded to a server.

    import { imageToDataUrl } from './utils/image-to-url';
    
    // Assuming 'file' is a File object from an input event
    async function handleFile(file: File) {
      try {
        const dataUrl = await imageToDataUrl(file);
        console.log('Data URL:', dataUrl);
        // You can now use this string as the 'src' for an <img> element
      } catch (error) {
        console.error('Failed to convert image:', error);
      }
    }