KineticJS - 如何在按钮上更改图像src单击 [英] KineticJS - How to Change Image src on Button Click
问题描述
我试图通过点击按钮更改kineticjs阶段中图像的src。
I'm trying to change the src of an image in my kineticjs stage on a button click.
我有一个可拖动的图像(在这种情况下是darth-vader )和顶部的静态图像(在这种情况下是猴子)。点击一个按钮,我希望能够用新的替换可拖动的图像(yoda)
I have a draggable image (in this case darth-vader) and a static image on top (in this case monkey). On the click of a button i want to be able to replace the draggable image with a new one (yoda)
JSFiddle可以在这里看到:
JSFiddle can be seen here:
我认为如下:
btn.addEventListener("click", function (event) {
mainImage.src = path+'yoda.jpg';
layer.removeChildren();
draw(mainImage,true);
draw(foregroundImage,true);
});
将完成它:首先通过更新src,然后删除所有对象并以正确的顺序重新绘制它们。
would accomplish it: first by updating the src, then removing all objects and redrawing both again in the correct order.
出于某种原因,虽然我得到2个yoda图像放在阶段 - 1正确落后但另一个高于其他所有...
For some reason though i get 2 yoda images placed on the stage - 1 correctly behind but another above everything else...
推荐答案
而不是删除所有孩子并将其添加回来,可以使用KineticJS <$轻松交换图像源c $ c> setImage 函数并传入Javascript图像对象: http://kineticjs.com/docs/Kinetic.Image.html#setImage
Instead of removing all the children and adding them back, you can swap image sources easily by using the KineticJS setImage
function and passing in a Javascript Image Object: http://kineticjs.com/docs/Kinetic.Image.html#setImage
我更新了你的抽奖
函数使得它需要一个id和name,以便我们以后可以选择Kinetic Image对象:
I updated your draw
function so that it takes an id and name so that we can select the Kinetic Image object later:
// 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;
}
然后这是你的更新点击功能:
and then here is your update click function:
// Change draggable Image
btn.addEventListener("click", function (event) {
layer.get('#mainImageId')[0].setImage(mainImage2); //get the object with id "mainImageId"
layer.draw();
});
另外,我在mainImage onload函数中移动了你的 foregroundImage
加载函数,我们确保在 mainImage
之后将Monkey添加到舞台上:
Also, I moved your foregroundImage
load function inside the mainImage onload function so that we make sure the Monkey is added to the stage after the 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';
这篇关于KineticJS - 如何在按钮上更改图像src单击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!