问题
I'm creating a script where image is draggable and can change the image source when double clicked.
Moving the image works ok and when double clicking the image (event is dblclick) the image changes but same time appears as double where another identical image appears in the original position.
Code is:
var picture = new Image();
picture.onload = function() {
var picture = new Kinetic.Image({
x: 10,
y: 10,
image: picture,
draggable: true,
width: 100,
height: 200
});
picture.on('dblclick', function() {
picture.src = 'images/picture2.jpg';
});
layer.add(picture);
stage.add(layer);
}
picture.src = 'images/picture1.jpg';
What am I doing wrong?
回答1:
That's because every time image.src is changed, image onload event is triggered. and onload event creates a new Kinetic Image and add to the layer. Here is my version of your source code.
$( function() {
var stage = new Kinetic.Stage({
container: 'container',
width: 578,
height: 200
});
var layer = new Kinetic.Layer();
var yoda = new Kinetic.Image({
x: 140,
y: stage.getHeight() / 2 - 59,
width: 106,
height: 118,
draggable:true
});
var images =[
'http://www.html5canvastutorials.com/demos/assets/yoda.jpg',
'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg',
'http://www.html5canvastutorials.com/demos/assets/wood-pattern.png'
];
var imgIndex = 0;
var imageObj = new Image();
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/yoda.jpg';
imageObj.onload = function() {
yoda.setImage(imageObj);
layer.draw();
};
yoda.on('dblclick',function() {
imageObj.src = images[ imgIndex++ % 3 ];
})
layer.add(yoda);
stage.add(layer);
});
I believe you follow the tutorial of the site, but it's not always correct. Also, please remember not to use the same variable picture on your source for image and kinetic object. it's very confusing
来源:https://stackoverflow.com/questions/14670896/draggable-image-event-in-kinect