setImage
您可以通过使用 KineticJS函数并传入 Javascript 图像对象来轻松交换图像源,而不是删除所有子元素并重新添加它们:http: //kineticjs.com/docs/Kinetic.Image.html#setImage
我更新了你的draw
函数,让它接受一个 id 和 name,以便我们稍后可以选择 Kinetic Image 对象:
// 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;
}
然后这是您的更新点击功能:
// Change draggable Image
btn.addEventListener("click", function (event) {
layer.get('#mainImageId')[0].setImage(mainImage2); //get the object with id "mainImageId"
layer.draw();
});
jsfiddle
此外,我将您的foregroundImage
加载函数移到 mainImage 的 onload 函数中,以便我们确保将 Monkey 添加到舞台之后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';