0

我正在使用 Konvajs,我有一组文本,并且我希望不允许在画布之外拖动组,我尝试使用 dragBoundFunc 解决了这个问题,但这对我没有帮助,现在我只是尝试更改组位置在 dragmove 期间,但是 setPosition、setAbslutePosition,没有任何东西可以让我更改组位置

stage.on('dragmove', (e) => stageOnDragMove(e, layer));
const stageOnDragMove = (e: Konva.KonvaEventObject<any>, layer: Konva.Layer) => {

    const selectionGroup = layer.findOne('#selection-group');
    const transformer = layer.findOne<Konva.Transformer>('Transformer');

    if (selectionGroup?.hasName('text-group')) {
        const pos = selectionGroup.getClientRect({});

        if (pos.x <= 0 || pos.y <= 0) {
            selectionGroup.setAbsolutePosition({
                x: 0,
                y: 0
            });
            layer.draw();
        }
    }

    transformer.attachTo(selectionGroup);
};
4

1 回答 1

1

您可以使用此功能来限制拖放和调整功能以限制其边界:

shape.on('dragmove transform', () => {
  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)
})

演示:https ://jsbin.com/rofupicupu/edit?html,js,output

于 2020-04-02T15:40:25.260 回答