2

community. I need to draw an arrow with the mouse using KonvaJS. I do not use React. It's the first time I use KonvaJS. I have searched information for solving this problem but I found nothing. I also read the documentation of this library but I found only how to draw a basic arrow. I will appreciate your help. Thank you so much!

  • 1
    Can you post a png image how the arrow will look like? – Chris P Oct 27 '20 at 01:13
  • @ChrisP Of course. Let me show you exactly what I want to do: https://codesandbox.io/s/w12qznzx5?file=/src/index.js In this link there's a whiteboard that allows you draw arrows. I want to draw arrows like those. My intention is to design a whiteboard like that without using React. – Edgar Alejandro Aldana Oct 27 '20 at 11:53

1 Answers1

3

There are many ways to draw an arrow. You can follow Free drawing Konva Demo, but use arrow instead of a line.

The simplest solution is to use mousedown - to create a line, mousemove to update line position, mouseup - to finish line.

let arrow;
stage.on('mousedown', () => {
   const pos = stage.getPointerPosition();
    arrow = new Konva.Arrow({
      points: [pos.x, pos.y],
      stroke: 'black',
      fill: 'black'
    });
    layer.add(arrow);
    layer.batchDraw();
});

stage.on('mousemove', () => {
  if (arrow) {
      const pos = stage.getPointerPosition();
      const points = [arrow.points()[0], arrow.points()[1], pos.x, pos.y];
      arrow.points(points);
      layer.batchDraw();
  }
});

stage.on('mouseup', () => {
  arrow = null;
});

Demo: https://jsbin.com/lefivihibu/2/edit?html,js,output

lavrton
  • 18,973
  • 4
  • 30
  • 63