ps0604
ps0604

Reputation: 1071

Avoid dragging unintentionally in Raphael

In this jsFiddle I have a Raphael canvas with a rect that can be clicked or dragged.

If you move the mouse to the rect and then click it, you may slightly move it (the text will show you that). I need in my application to handle the click and ignore the drag movement when the user intended to click. For example, I need to enable the drag only if it's greater than, say, 5 px. Is there a way to make Raphael not move the rect if the intention is just to click?

var paper = Raphael("canvas", 600, 600); 
var title = this.paper.text(50, 10, 'click on the square');
var rect = this.paper.rect(20, 20, 30, 30);
rect.attr('fill', 'black')

var start = function () {
      this.odx = 0;
      this.ody = 0;
},
move = function (dx, dy) {
      title.attr('text', 'mouse moved')
      this.translate(dx - this.odx, dy - this.ody);
      this.odx = dx;
      this.ody = dy;
},
up = function () {};

rect.drag(move, start, up);

rect.mousedown(function(e){
      title.attr('text', 'mouse down')      
})

Upvotes: 1

Views: 84

Answers (1)

Temo Tchanukvadze
Temo Tchanukvadze

Reputation: 1522

You can store initial coordinates when the movement has started and ignore while the distance between current coordinates and initial coordinates is less than x pixels.

var paper = Raphael("canvas", 600, 600); 
var title = this.paper.text(50, 10, 'click on the square');
var rect = this.paper.rect(20, 20, 30, 30);
var PX_TO_IGNORE = 5; // pixels to ignore

rect.attr('fill', 'black')

var start = function () {
      this.odx = 0;
      this.ody = 0;
      this.initialCor = null;
},
move = function (dx, dy) {
  // check if not initialized(if it`s first click)
  if(this.initialCor == null) {
    this.initialCor = {x: dx, y: dy};
    return;
  }

  // ignore PX_TO_IGNORE pixels(basically circle with radius PX_TO_IGNORE)
  if(distance(this.initialCor.x, dx, this.initialCor.y, dy) < PX_TO_IGNORE ) {
    return;
  }

  title.attr('text', 'mouse moved')

  this.translate(dx - this.odx, dy - this.ody);
  this.odx = dx;
  this.ody = dy; 
},
up = function () {
  title.attr('text', 'mouse up')
};

rect.drag(move, start, up);

rect.mousedown(function(e){
  title.attr('text', 'mouse down')      
})

// helper function to calcuate distance between two coordinates
function distance(x1,x2,y1,y2) {
    return Math.sqrt( Math.pow((x1-x2), 2) + Math.pow((y1-y2), 2) );
}

http://jsfiddle.net/htLn819y/4/

Upvotes: 2

Related Questions