Search code examples
konvajs

Image must be added to group before group added to layer?


I'm finding a potential bug in KonvaJS. Or I'm not sure about the capabilities...

1) Create a layer and add it to stage

2) Create a group and add it to layer

3) Create an Image node and add it to group (Note my images are loaded using Konva.Image.fromURL which waits for the image to load then adds it to the group.)

Result: Image does not appear.

But if you add the image to the group then add the group to the layer, the image appears. This is going to cause problems if I want to attach an image to a group dynamical if it just disappears.

I'm trying to create the concept of a tray or plate. Where the user can place items onto the plate. If the user drags the plate it creates a group with all the intersecting nodes and moves them all together. At drag end it releases all the objects back to the user.

EDIT: The problem I was experiencing had to do with group coordinates as I mentioned in my comment bellow.

"I think I misunderstood, for the longest time how positioning works with groups. Read the comments: jsfiddle.net/jusatx6s"

LL: Make sure you're checking the position of the nodes your are rendering and that they do appear on screen.


Solution

  • I have created a plunkr and followed steps which you have mentioned. Everything is working fine. Here's my code.

    var width = window.innerWidth;
    var height = window.innerHeight;
    var stage = new Konva.Stage({
      container: 'container',
      width: width,
      height: height
    });
    // 1. created layer added it to stage.
    var layer = new Konva.Layer();
    stage.add(layer);
    // 2. created group added it to layer
    var group = new Konva.Group({
            x: 120,
            y: 40,
            rotation: 20
    });
    
    layer.add(group);
    var src = 'https://konvajs.github.io/assets/yoda.jpg';
    // 3. Create an Image node and add it to group
    Konva.Image.fromURL(src, function(yoda) {
      console.log(yoda);
      yoda.setAttrs({
        x: 50,
        y: 50,
        width: 106,
        height: 118
      });
      // 4. Add it to group.
      group.add(yoda);
      layer.batchDraw(); // It's required to draw changes.
    });
    

    Here's the plnkr to play around. Please let me know if I have missed anything.