Draggable image event in Kinect

天涯浪子 提交于 2019-12-12 03:43:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!