且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在KineticJS中替换图像

更新时间:2023-02-19 14:30:29

您的代码如下所示:

$('#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.

最后,每次用户点击按钮并将其添加到图层时,您都将创建一个新的Kinetic.Image。没关系!继续这样做。但你也想删除旧的Kinetic.Image。

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.

因此之前将Kinetic.Image添加到图层中,您要从图层中删除任何现有图片: layerKnocker.removeChildren()将删除图层中的所有内容。

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.