-->

KineticJS - replacing image within a group

2019-09-09 19:57发布

问题:

Please see this Link

When the canvas loads there are 2 images: Yoda and Darth Vader.

I want to be able to click on Yoda (to select it) and then click on the "change" button under the canvas. This button click should replace Yoda with Darth Vader and still keep the "2nd" Darth Vader selected.

My code is as follows:

  function replaceImage(i, callback) {

      selectedGroup.destroy();

      var images = {};
      images[i] = new Image();
      images[i].onload = function() {
          callback(i,images);
      };
      images[i].src = sources[i].path;    
  }  

I tried it with selectedGroup.removeChildren() and then adding the image manually but it doesn't work either - ie

function replaceImage(i) {

      selectedGroup.removeChildren();

      var image = new Image();

        var newImage = new Kinetic.Image({
            id: i,
            image: image,
            x: 0,
            y: 0,
            width: sources[i].width,
            height: sources[i].height,
            name: 'image',
            stroke: 'red',
            strokeWidth: 2,
            strokeEnabled: false        
          });

        newImage.src = sources[i].path;
        selectedGroup.add(newImage);                  
  }  

Can anyone see what I am doing wrong?

Thanks for any help!

回答1:

Instead of destroying the Yoda object and creating a new Vader object, how about just using setImage to replace the Yoda Image with a Vader image?

Something like:

// get the image object from the selected group
var ImageObjects = selectedGroup.get("Image");
var ImageObject=ImageObjects.toArray()[0];

// keep the Kinetic.Image object
// but replace its image
ImageObject.setImage(myNewImage);


标签: kineticjs