-->

在KineticJS更换图片(Replacing an image in KineticJS)

2019-09-28 02:07发布

我试图建立使用KineticJS一个web应用程序,我基本都运行在它增加了图像的画布(在KineticJS阶段)负载的功能。 每当函数,虽然运行时,它再次把图象现有的一个,在那里,因为我需要它来代替一个是目前在舞台下方。 我知道这件事情与我创建一个新的图像对象的每个函数加载时间,但我很困惑,为什么它的定位是不同的(下方)。 我已经模拟了相同的事件在这里: http://jsfiddle.net/UCvbe/ -如果你点击按钮几次,下面的图片重复。 当用户选择一个吹毛求疵的最终功能会跑,所以这样它才能知道绘制银门环等最后的函数必须接受一个参数,如“银”

任何帮助将不胜感激!

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



文章来源: Replacing an image in KineticJS