KineticJS - replacing image within a group

大兔子大兔子 提交于 2020-01-06 10:21:36

问题


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


来源:https://stackoverflow.com/questions/17702319/kineticjs-replacing-image-within-a-group

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