如何使用KonvaJS用鼠标绘制箭头?

问题描述

社区。我需要使用KonvaJS用鼠标绘制箭头。我不使用React。这是我第一次使用KonvaJS。我已经搜索解决此问题的信息,但没有发现任何问题。我也阅读了该库的文档,但只发现了如何绘制基本箭头。感谢您的帮助。非常感谢!

解决方法

有很多绘制箭头的方法。您可以遵循Free drawing Konva Demo,但使用箭头代替线条。

最简单的解决方案是使用mousedown-创建一条线,使用mousemove更新线的位置,使用mouseup-完成线。

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;
});

演示:https://jsbin.com/lefivihibu/2/edit?html,output