首页 > 解决方案 > 如何使用 KonvaJS 用鼠标绘制箭头?

问题描述

社区。我需要使用 KonvaJS 用鼠标绘制箭头。我不使用反应。这是我第一次使用 KonvaJS。我已经搜索了解决此问题的信息,但我一无所获。我还阅读了这个库的文档,但我只发现了如何绘制基本箭头。我会感谢你的帮助。太感谢了!

标签: javascriptkonvajs

解决方案


画箭头的方法有很多种。您可以按照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,js,output


推荐阅读