Skip to content Skip to sidebar Skip to footer

Replacing An Image In Kineticjs

I'm trying to build a web app using KineticJS, I basically have a function which runs on load which adds an image to a canvas (stage in KineticJS). Each time the function runs thou

Solution 1:

Your code looks like this:

$('#testBtn').click(function() {

var stageKnocker = newKinetic.Stage({
    container: "canvas-overlay",
    width: 402,
    height: 470
});
var layerKnocker = newKinetic.Layer();

var imageObj = newImage();
imageObj.onload = function(){
    var image = newKinetic.Image({
    x: 193,
    y: 110,
    image: imageObj,
    width: 25,
    height: 50,
    draggable: true
     });
     layerKnocker.add(image);
     stageKnocker.add(layerKnocker);
 };
 imageObj.src = "http://shop.windowrepairshop.co.uk/WebRoot/Store3/Shops/es115683_shop/49E6/ECF2/0C60/3750/10B1/50ED/8970/710D/V6GP_0020_gold_0020_plate_0020_vic_0020_urn_0020_LArge.jpg";

})

The first problem is that you are creating a new Stage each time a user clicks the button. Don't do that--you only want one stage.

You're also creating a new layer each time a user clicks the button. Don't do that. You only need & want a single layer.

Finally, you are creating a new Kinetic.Image each time a user clicks the button and adding it to the layer. That's fine! Keep doing that. But you also want to remove the old Kinetic.Image. If you don't, you will just keep adding images, not replacing them.

So before adding the Kinetic.Image to the layer, you want to remove any existing images from the layer: layerKnocker.removeChildren() will remove everything in the layer.

When you're done, you will have a single stage, a single layer, and at any point in time a single image.

Post a Comment for "Replacing An Image In Kineticjs"