Search code examples
canvaskonvajs

Boolean operations on Konva Shapes


I was wondering how I can do boolean operations on Konva.js? I'd like to subtract an Konva.Line from a Konva.Rect.

Are there any build-in functions for this, or do I need an outside library?


Solution

  • There is no built-in function for boolean operation on shapes in Konva.

    But you can use group + caching + globalCompositeOperation as a workaround.

    1. Draw rectangle
    2. Draw a line with globalCompositeOperation = destination-out to "cut" it from rect
    3. Put both rectangle and line into grou
    4. Cache the group, so globalCompositeOperation of a line doesn't effect the rest of your drawings.

    const stage = new Konva.Stage({
      container: 'container',
      width: window.innerWidth,
      height: window.innerHeight
    });
    
    const layer = new Konva.Layer();
    stage.add(layer);
    
    const group = new Konva.Group({ draggable: true });
    layer.add(group);
    
    const shape = new Konva.Rect({
      x: 50,
      y: 50,
      width: 100,
      height: 100,
      fill: 'green'
    });
    group.add(shape);
    
    const line = new Konva.Line({
      x: 50,
      y: 50,
      points: [20, 20, 50, 20, 50, 50],
      closed: true,
      fill: 'black',
      globalCompositeOperation: 'destination-out'
    })
    group.add(line);
    
    group.cache();
      <script src="https://unpkg.com/konva@^9/konva.min.js"></script>
      <div id="container"></div>