how to use draggable and click separately in kineticjs?

吃可爱长大的小学妹 提交于 2019-12-12 03:54:32

问题


how to use draggable and click on same node in kineticjs? when using draggable then a click event fires also after drag.

in jsfiddle, http://jsfiddle.net/matobaa/LZ5tt/

Here is the code...

var stage = new Kinetic.Stage({
  container: 'container', width: 640, height: 480
});
var layer = new Kinetic.Layer();
var oval = new Kinetic.Ellipse({
  x: 100, y: 100, radius: 50, stroke: 'red',
  draggable: true,
});
oval.on('click', function(evt) {
  alert("clicked!"); // Will not be triggered after drag
})
layer.add(oval);
stage.add(layer);

I'm using kineticjs 4.4.1. please help.


回答1:


You need to detect drag state. Es:

var indrag = false;
oval.on('dragstart', function(evt){
    indrag = true;
});
oval.on('dragend', function(evt){
    indrag = false;
});

and then:

oval.on('click', function(evt) {
    if (!indrag){
        alert("clicked!"); // Will not be triggered after drag
    }
})



回答2:


You can do it by checking the current event functioning through a variable value. jsFiddle: http://jsfiddle.net/LZ5tt/4/

    var stage = new Kinetic.Stage({
      container: 'container', width: 640, height: 480
    });
    var layer = new Kinetic.Layer();
    var oval = new Kinetic.Ellipse({
        x: 100, y: 100, radius: 50, stroke: 'red',
      draggable: true,
    });
    var drag = false;
    oval.on('dragstart', function(event){
        drag = true;
    });
    oval.on('dragend', function(event){
        drag = false;
    });
    oval.on('click', function(event) {
        if (!drag){
            alert("I'm clicked!");
        }
    })
    layer.add(oval);
    stage.add(layer);



回答3:


Just some useful tip as for KineticJS version 5.1.0.

In case of detecting clicks over a Kinetic Stage, you might be experiencing that after finishing a drag on a shape, the click event on the stage will fire.

What I suggest is to set a control variable to "true" inside the dragstart; and then, check that variable inside the click event triggered, you set it to "false" and then return to exit the code block. This way you will not prevent the click event, but nothing will happen as it is handled.

Allow me to borrow some code from the answer above:

var indrag = false;

oval.on('dragstart', function(evt){
    indrag = true;
});
oval.on('dragend', function(evt){

});

stage.on('click', function(evt) {
    if (indrag){
        indrag = false;
        return;
    }

    // else, it is a valid click, then do what you need to do...
})


来源:https://stackoverflow.com/questions/15904712/how-to-use-draggable-and-click-separately-in-kineticjs

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