Replacing an image in KineticJS

笑着哭i 提交于 2019-12-24 16:09:11

问题


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 though, it is adding the image again underneath the existing one, where as I need it to replace the one that is currently on the stage. I know it's something to do with me creating a new image object each time the function is loaded, but I'm confused as to why it's positioning is different (underneath). I have simulated the same event here: http://jsfiddle.net/UCvbe/ - If you click the button several times, the image duplicates below. The final function will be ran when a user selects a knocker, therefore the final function must accept a parameter eg 'silver' so that it knows to draw the silver knocker etc.

Any help will be greatly appreciated!


回答1:


Your code looks like this:

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

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

var imageObj = new Image();
imageObj.onload = function(){
    var image = new Kinetic.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.



来源:https://stackoverflow.com/questions/11363256/replacing-an-image-in-kineticjs

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