I'm trying to change the src of an image in my kineticjs stage on a button click.
I have a draggable image (in this case darth-vader) and a static image on top (in this case monkey). On the click of a button i want to be able to replace the draggable image with a new one (yoda)
JSFiddle can be seen here:
I thought the following:
btn.addEventListener("click", function (event) {
mainImage.src = path+'yoda.jpg';
layer.removeChildren();
draw(mainImage,true);
draw(foregroundImage,true);
});
would accomplish it: first by updating the src, then removing all objects and redrawing both again in the correct order.
For some reason though i get 2 yoda images placed on the stage - 1 correctly behind but another above everything else...
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...
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#setImageI updated your
draw
function so that it takes an id and name so that we can select the Kinetic Image object later:and then here is your update click function:
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 themainImage
: