KineticJS - How to Change Image src on Button Clic

2020-04-01 07:58发布

问题:

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:

http://jsfiddle.net/SkVJu/33/

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...

回答1:

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


回答2:

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...