相关文章推荐
打盹的稀饭  ·  失败的生成数 - Visual ...·  1 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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,
            layer.draw();
    transformer.attachTo(selectionGroup);

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

It's ok for shape, but I have problem, when I add texts in group, please see my code, how can I fix it? jsbin.com/gibufiw/edit?html,js,output – Programmer Apr 2, 2020 at 19:39

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.