0

I am working on konva js. I am working on an app that lets users create custom shapes. and after creation they can resize it by mouse, connect two shapes by a line. So far the feature drawing custom shape and their connecting by line is complete.

Now I want to show dots around the custom shape when user hovers on the custom shape just like this

when user hovers

P.S I have seen this from https://app.diagrams.net/. I want to build drawing app same like it.If someone can navigate me to the resources from where I can build drawing app like this, it would be really helpful.

1 Answers1

0

You can use mouseenter and mouseleave events to show/hide anchors for the shape.

It is up to you to choose how to implement anchors. It can be custom anchors like in https://konvajs.org/docs/sandbox/Modify_Curves_with_Anchor_Points.htm or it can be Konva.Transformer https://konvajs.org/docs/select_and_transform/Basic_demo.html.

On mouseenter you can show anchors. Hiding anchors is a bit tricker for the demo I will hide anchors when mouse is too far away from the shape. We can't use mouseleave as is here, because it will trigger hide when we simply hover Konva.Transformer.

In the demo, try to hover the circle.

const stage = new Konva.Stage({
  container: 'container',
  width: window.innerWidth,
  height: window.innerHeight
});

const layer = new Konva.Layer();
stage.add(layer);

const shape = new Konva.Circle({
  x: stage.width() / 2,
  y: stage.height() / 2,
  radius: 50,
  fill: 'green'
});
layer.add(shape);

const tr = new Konva.Transformer();
layer.add(tr);

// from https://stackoverflow.com/questions/5254838/calculating-distance-between-a-point-and-a-rectangular-box-nearest-point
function getDistance(rect, p) {
  var dx = Math.max(rect.x - p.x, 0, p.x - (rect.x + rect.width));
  var dy = Math.max(rect.y - p.y, 0, p.y - (rect.y + rect.height));
  return Math.sqrt(dx*dx + dy*dy);
}

shape.on('mouseenter', () => {
  tr.nodes([shape]);
});



stage.on('mousemove', () => {
  if (!tr.nodes().length) {
    return;
  }
  if (tr.isTransforming()) {
    return;
  }
  const rect = shape.getClientRect();
  const dist = getDistance(rect, stage.getPointerPosition());
  if (dist > 60) {
    tr.nodes([]);
  }
});

layer.draw();
  <script src="https://unpkg.com/konva@^8/konva.min.js"></script>
<div id="container"></div>
lavrton
  • 18,973
  • 4
  • 30
  • 63