0

I'm using Konvajs, I have group of texts, and I want don't allow drag group outside of the canvas, I'm tried solved that using dragBoundFunc, but that don't help me, now I just try change group position during dragmove, but setPosition, setAbsloutePosition, nothing allow me to change group position

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);
};
Programmer
  • 65
  • 7

1 Answers1

1

You can use this function to limit drag&drop and resize feature to limit its boundaries:

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

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

lavrton
  • 18,973
  • 4
  • 30
  • 63
  • It's ok for shape, but I have problem, when I add texts in group, please see my code, how can I fix it? https://jsbin.com/gibufiw/edit?html,js,output – Programmer Apr 02 '20 at 19:39
  • Just make the only group draggable. https://jsbin.com/buyewepilo/1/edit – lavrton Apr 02 '20 at 19:50