Konva HTML5 Canvas Framework

repository·master·Indexed 12 days ago

https://github.com/konvajs/konva

An HTML5 2D canvas JavaScript framework for building high-performance interactive graphics, editors, and diagrams. Version 10.3.0 supports node nesting, layering, animations, and event handling for desktop and mobile. It includes a comprehensive API for managing containers, shapes, and filters, and can be run in both browser and Node.js environments using backends like canvas or skia-canvas.

Tokens
8K
Snippets
34
Records
44
Agent score
96%

What's inside Konva

  1. Run Konva in a NodeJS environment

    master

    To use Konva in Node.js, you must manually install a rendering backend like canvas or skia-canvas. When using a backend in Node, you do not need to provide a container attribute in the Stage configuration.

    # node-canvas backend
    npm install konva canvas
    
    # skia-canvas backend
    npm install konva skia-canvas
    import Konva from 'konva';
    import 'konva/canvas-backend'; // or import 'konva/skia-backend';
    
    const stage = new Konva.Stage({
      width: 500,
      height: 500,
    });
  2. Use the Konva Minimal Bundle

    master

    To reduce bundle size, you can import only the Core module. This provides Stage, Layer, FastLayer, Group, Shape, and basic utilities (including drag&drop and animations), but excludes shapes and filters. You can then selectively import only the specific shapes or filters you need, which will automatically inject them into the Konva object.

    import Konva from 'konva/lib/Core';
    
    // Import specific shapes to inject them into Konva
    import { Rect } from 'konva/lib/shapes/Rect';
    
    // Or use them directly
    var rect1 = new Rect();
    // or:
    var shape = new Konva.Rect();
    
    // Import filters as needed
    import { Blur } from 'konva/lib/filters/Blur';
  3. Use Konva.Layer to organize and render shapes

    master

    A Layer is a container tied to its own canvas element. It is used to hold Group or Shape objects. Layers are typically added to a Stage. Each layer manages its own scene canvas and a hidden hit canvas used for event detection.

    To use a layer, create a new instance and add it to your stage. You can then add shapes or groups directly to the layer.

    var layer = new Konva.Layer();
    stage.add(layer);
    // now you can add shapes, groups into the layer
  4. Quick Look: Create a basic Konva stage and shape

    master

    This example demonstrates the fundamental workflow of Konva: creating a Stage, adding a Layer, and adding a shape (like a Rect) to that layer. It also shows how to enable draggable: true and handle mouse events like mouseover and mouseout.

    <script src="https://unpkg.com/konva@10.0.0-1/konva.min.js"></script>
    <div id="container"></div>
    <script>
      var stage = new Konva.Stage({
        container: 'container',
        width: window.innerWidth,
        height: window.innerHeight,
      });
    
      // add canvas element
      var layer = new Konva.Layer();
      stage.add(layer);
    
      // create shape
      var box = new Konva.Rect({
        x: 50,
        y: 50,
        width: 100,
        height: 50,
        fill: '#00D2FF',
        stroke: 'black',
        strokeWidth: 4,
        draggable: true,
      });
      layer.add(box);
    
      // add cursor styling
      box.on('mouseover', function () {
        document.body.style.cursor = 'pointer';
      });
      box.on('mouseout', function () {
        document.body.style.cursor = 'default';
      });
    </script>
  5. Configure Konva.Layer options

    master

    When creating a Layer, you can pass a LayerConfig object to customize its behavior:

    • clearBeforeDraw (Boolean): Determines if the canvas is cleared before each layer draw. Defaults to true. Set to false if you want to preserve previous drawings.
    • hitGraphEnabled (Boolean): DEPRECATED. Use layer.listening(boolean) instead. Disabling the hit graph increases draw performance but disables mouse/touch event detection.
    • imageSmoothingEnabled (Boolean): Controls the imageSmoothingEnabled flag of the canvas context.
    export interface LayerConfig extends ContainerConfig {
      clearBeforeDraw?: boolean;
      hitGraphEnabled?: boolean;
      imageSmoothingEnabled?: boolean;
    }
  6. Configure Wedge properties

    master

    The WedgeConfig object accepts the following properties:

    PropertyTypeDefaultDescription
    radiusnumber0The radius of the wedge. Affects width and height.
    anglenumber0The angle of the wedge in degrees.
    clockwisebooleanfalseWhether the arc is drawn clockwise or counter-clockwise.
    fillstringThe fill color.
    strokestringThe stroke color.
    strokeWidthnumberThe stroke width.
  7. Configure RegularPolygon properties

    master

    The RegularPolygon shape accepts the following configuration properties via its constructor or getter/setter methods:

    • sides (number): The number of sides of the polygon. Defaults to 0.
    • radius (number): The radius of the polygon. Defaults to 0. Note that changing the radius affects the size of the shape.
    • cornerRadius (number | number[]): The radius of the corners. If an array is provided, it allows for different corner radii (e.g., for a pentagon, an array of 5 numbers). Defaults to 0.
  8. Configure global Konva settings

    master

    The Konva object provides several global configuration properties that affect the behavior of all Konva nodes and the rendering engine. Many of these should be set before initializing your Konva components.

    Rendering & Performance

    • autoDrawEnabled (default: true): Determines if Konva automatically updates the canvas on any changes.
    • pixelRatio (default: window.devicePixelRatio or 1): Sets the global pixel ratio. Set this before any component initialization to override automatic detection.
    • releaseCanvasOnDestroy (default: true): If true, Konva releases canvas elements on destroy. This is useful for avoiding memory leaks in Safari on macOS/iOS.
    • legacyTextRendering (default: false): Enables legacy text rendering with a "middle" baseline.
    • hitOnDragEnabled (default: false): Enables hit detection during dragging. Useful for debugging intersections, but can impact performance.

    Interaction & Input

    • angleDeg (default: true): If true, angle properties (like rotation) use degrees. If false, they use radians.
    • dragDistance (default: 3): The distance a pointer must move before a drag operation is considered started.
    • dragButtons (default: [0, 1]): An array of mouse button IDs allowed for drag and drop (e.g., 0 for left, 1 for middle, 2 for right).
    • capturePointerEventsEnabled (default: false): If true, Konva captures touch events and binds them to the initial touchstart target, mimicking standard DOM behavior.
    • pointerEventsEnabled (default: true): Enables or disables pointer events.

    Debugging

    • showWarnings (default: true): Controls whether Konva displays warnings about errors or incorrect API usage.
    • enableTrace (default: false): Enables tracing.
    // Example: Configuring global settings before initialization
    Konva.pixelRatio = 1;
    Konva.angleDeg = false; // Use radians instead of degrees
    Konva.dragButtons = [0, 2]; // Enable left and right mouse buttons
    Konva.showWarnings = false;
  9. Use the RGBA filter to adjust color and transparency

    master

    The Konva.Filters.RGBA filter allows you to manipulate the color components (red, green, blue) and the alpha (transparency) of a node. To use it, you must first call .cache() on the node, then apply the filter using .filters([Konva.Filters.RGBA]), and finally set the desired color values using the specific getter/setter methods.

    node.cache();
    node.filters([Konva.Filters.RGBA]);
    node.red(120);
    node.green(200);
    node.blue(50);
    node.alpha(0.3);