0

I am using KonvaJs in my project. I am using Konva.Group to club some items like Konva.Image, Konva.Rect together. But I am facing some challenges while placing them at particular position with mousemove event. I have Konva.Group like this:

 var group = new Konva.Group({
      x: 0,
      y: 0
    });

And a image and rectangle like this

var border = new Konva.Rect({
      x: 115,
      y: 35,
      width: 116,
      height: 128,
      fill: 'grey'
    });

yoda = new Konva.Image({
        x: 120,
        y: 40,
        image: imageObj,
        width: 106,
        height: 118
      });

Here's the plunkr.

Now what I want to do is to move the group to the position where mouse pointer is. To do so I am doing this:

stage.on('mousemove', function(e) {
      var point=stage.getPointerPosition();
      //Don't know why this is not puttig the group childern poperly
      //group.position(stage.getPointerPosition());
      yoda.position(point);
      border.position({
        x: point.x-5,
        y: point.y-5
      })
      layer.batchDraw();
    });

Since here I only have two element so I can move them one by one but if the number of elements or children in my group will increases. I can not move all of them one by one. I tried to move the entire group but it is not following pointer position. I want to understand how I can put the piece in such a way that I just do group.position(position) and the clubbed pieces start following the mouse pointer. And also what is the relation between the Coordinates of Group and it's children.

Hitesh Kumar
  • 3,508
  • 7
  • 40
  • 71

1 Answers1

2

You may have unexpected behaviour because your children nodes are moved inside a group.

When you created the image in had x = 120 y = 140. When you set group position to (for example) x= 100 y = 100, image will be placed in x = 210 (120 + 100) y = 240 (140 + 100).

Just decrease positions of children elements:

      yoda = new Konva.Image({
        x: 5,
        y: 5,
        image: imageObj,
        width: 106,
        height: 118
      });

      group.add(border);
      group.add(yoda);

http://plnkr.co/edit/TkTGAw0eGHF5flbVYLuQ?p=preview

lavrton
  • 18,973
  • 4
  • 30
  • 63