1

我正在尝试使用 React Konva 在图像上绘制一个矩形,并获取其 4 个角的坐标。我已经相当准确地计算并返回了4个角的坐标,但问题是我仍然无法实现dragBoundFunc(拖动时在画布中绑定矩形)和boundBoxFunc(在变换时绑定画布中的矩形(旋转, 规模))。

我能想到的一种解决方案是获取 4 个角的最小和最大 X、Y 坐标,然后如果画布的最小 < 0 和最大 > 尺寸则返回 false。但是我还没有成功,你可以在这里查看我的沙箱。谢谢你的帮助。

4

1 回答 1

1

对于拖动功能,您可以这样做:

shape.on('dragmove', () => {
  const box = shape.getClientRect();
  const absPos = shape.getAbsolutePosition();
  const offsetX = box.x - absPos.x;
  const offsetY = box.y - absPos.y;
  
  const newAbsPos = {...absPos}
  if (box.x < 0) {
    newAbsPos.x = -offsetX;
  }
  if (box.y < 0) {
    newAbsPos.y = -offsetY;
  }
  if (box.x + box.width > stage.width()) {
    newAbsPos.x = stage.width() - box.width - offsetX;
  }
  if (box.y + box.height > stage.height()) {
    newAbsPos.y = stage.height() - box.height - offsetY;
  }
  shape.setAbsolutePosition(newAbsPos)
});

上面的想法只是限制节点的绝对位置。

因为转换有点复杂,可能需要抛光才能顺利工作。但我试过这个:

let oldAttrs;
shape.on('transform', () => {
  const box = shape.getClientRect();
  const isOut = box.x < 0 || box.y < 0 || box.x + box.width > stage.width() || box.y + box.height > stage.height();
  
  if (isOut) {
    shape.setAttrs(oldAttrs);
  } else {
    oldAttrs = {...shape.getAttrs()};
  }
});

因此,如果形状的位置不在可见视口中,我们只需将属性重置回之前的值。

演示:https ://jsbin.com/gakelemuru/2/edit?js,output

于 2020-06-30T20:42:03.477 回答