Konvajs: How to change position of group of texts

我是研究僧i 提交于 2020-04-30 06:25:04

问题


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

回答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



来源:https://stackoverflow.com/questions/60969263/konvajs-how-to-change-position-of-group-of-texts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!