S4M
S4M

Reputation: 4671

Handling a "drop" event in javascript with Raphael

I am trying to build a board game in javascript with Raphael, which involves having the user drag and drop some pictures. I know Raphael objects have a method drag that enables pictures to be dragged.

I want the user to move a piece (represented by a picture) only according to the rules. To do this, I can write a method move in that way (in this example, a piece can only move by one square vertically):

move = function (dx, dy) {
    document.getElementById("xCoord").innerHTML = dx;
    document.getElementById("yCoord").innerHTML = dy;
startSquareX = coordToSquare(this.ox);
startSquareY = coordToSquare(this.oy);
newSquareX = coordToSquare(this.ox+dx);
newSquareY = coordToSquare(this.oy+dy);
var deltaX = newSquareX - startSquareX;
var deltaY = newSquareY - startSquareY;       
if((deltaX*deltaX + deltaY*deltaY)===1) {
    this.attr({x: this.ox + dx, y: this.oy+dy});                       
} else {
    this.attr({x: this.ox, y: this.oy});
}}

The code above enables to user to move a piece in the only squares in the board that the rules allow. I would prefer to have it sightly differently: - the user can drag a piece wherever she wants on the board - when the piece is dropped on a square, if the piece is moved according to the rules, then the piece is put where the user dropped it. Otherwise, it is put back on its initial square.

This is the second point I am unable to do, because I don't know how to handle the event "drop" with Raphael. Can somebody help?

Upvotes: 0

Views: 186

Answers (1)

MalSu
MalSu

Reputation: 541

There isn't a drop event in in Raphael but Element.drag has an event handler for onend. That's where you define your "drop".

Refer to this demo. Notice the up handler (view source) that is called when element stops being dragged.

Upvotes: 3

Related Questions