KineticJS - How to Change Image src on Button Click

倖福魔咒の 提交于 2019-12-01 14:13:06

Instead of removing all the children and adding them back, you can swap image sources easily by using the KineticJS setImage function and passing in a Javascript Image Object: http://kineticjs.com/docs/Kinetic.Image.html#setImage

I updated your draw function so that it takes an id and name so that we can select the Kinetic Image object later:

// Draw function
function draw(image,drag,id,name){
    if (typeof id == 'undefined') id = '';
   if (typeof name == 'undefined') name = '';
   var img = new Kinetic.Image({
        image: image,
        draggable: drag,
       id: id,
       name: name
    });
    layer.add(img);
    layer.draw(); 

    return img;
}

and then here is your update click function:

// Change draggable Image
btn.addEventListener("click", function (event) {
    layer.get('#mainImageId')[0].setImage(mainImage2); //get the object with id "mainImageId"
    layer.draw();
});

jsfiddle

Also, I moved your foregroundImage load function inside the mainImage onload function so that we make sure the Monkey is added to the stage after the mainImage:

// Define draggable image
var mainImage = new Image();
mainImage.onload = function () {
    draw(mainImage,true, 'mainImageId');
    // Define foreground image
    var foregroundImage = new Image();
    foregroundImage.onload = function () {
        draw(foregroundImage,false);
    };
    foregroundImage.src = path+'monkey.png';
};
mainImage.src = path+'darth-vader.jpg';

Wouldn't it be easier to load both images right away, create new Kinetic.Group of them, set one visible and other hidden, than just create function that will hide first and show second on click? Just asking cause i have similar issue to deal with, just that in my case exchange should be done among 5 different icons based on settings parameter that user can change...

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