Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KonvaJS: How to connect two shapes with an arrow?

I would like to use Konvajs to do below tasks:

  1. draw two rectangle groups on canvas. Each group contains a rectangle, text, and a circle
  2. When I use the mouse to drag from the circle, it draws an arrow while dragging.
  3. When I drop the arrow into another group, it stops drawing and connects the two groups edge to edge

Something like this:

example

Are there any native methods that support connections between shapes? Could anyone show me some examples please?

like image 267
Bo Hu Avatar asked May 17 '16 01:05

Bo Hu


1 Answers

I have connected Konva.Circles. But the logic for images will also be the same. Please find the plunkr

var width = window.innerWidth;
    var height = window.innerHeight;

    var stage = new Konva.Stage({
      container: 'container',
      width: width,
      height: height
    });

    var layer = new Konva.Layer();

    var circle = new Konva.Circle({
      x: stage.getWidth() / 2,
      y: stage.getHeight() / 2,
      radius: 40,
      fill: 'green',
      stroke: 'black',
      strokeWidth: 2,
      draggable: true
    });

    var circleA = new Konva.Circle({
      x: stage.getWidth() / 5,
      y: stage.getHeight() / 5,
      radius: 30,
      fill: 'red',
      stroke: 'black',
      strokeWidth: 2,
      draggable: true
    });

    var arrow = new Konva.Arrow({
      points: [circle.getX(), circle.getY(), circleA.getX(), circleA.getY()],
      pointerLength: 10,
      pointerWidth: 10,
      fill: 'black',
      stroke: 'black',
      strokeWidth: 4
    });

    function adjustPoint(e){
      var p=[circle.getX(), circle.getY(), circleA.getX(), circleA.getY()];
      arrow.setPoints(p);
      layer.draw();
    }

    circle.on('dragmove', adjustPoint);

    circleA.on('dragmove', adjustPoint);

    layer.add(circleA);
    // add the shape to the layer
    layer.add(circle);
    layer.add(arrow);

    // add the layer to the stage
    stage.add(layer);
like image 50
Hitesh Kumar Avatar answered Oct 19 '22 00:10

Hitesh Kumar