20

Webアプリにrapaeljsを使用しています。オブジェクトのドロップ可能な境界を設定したい。オブジェクトはドロップ可能な領域に移動できます。オブジェクトがドロップ可能領域に入ると、そのオブジェクトから抜け出す方法はありません。

4

1 に答える 1

63

Raphaelには、を介したドラッグアンドドロップのサポートが組み込まれています.drag()element.drag(start, move, up);3つの引数が、それぞれmousedown、movement、およびmouseupイベントを処理する作成する関数への3つの関数参照である形式で使用します。

とが開始位置を格納するために使用され、this.oxとが移動に使用される方法に注意してください。this.oydxdy

以下は、ボックスへのドラッグアンドドロップを実装しています。ボックスはいつでも移動できますが、「刑務所」ボックスに入れると、元に戻すことはできません。ボックスが刑務所に入ると、色が即座に変更され、機能が変更されたことをユーザーに通知します。

これは、後のボックスの位置の調整で実装さMath.min()れ、現在の位置に追加されます。Math.max()dxdy

var nowX, nowY, move = function (dx, dy) {
    // move will be called with dx and dy
    if (this.attr("y") > 60 || this.attr("x") > 60)
        this.attr({x: this.ox + dx, y: this.oy + dy}); 
    else {
        nowX = Math.min(60, this.ox + dx);
        nowY = Math.min(60, this.oy + dy);
        nowX = Math.max(0, nowX);
        nowY = Math.max(0, nowY);            
        this.attr({x: nowX, y: nowY });
        if (this.attr("fill") != "#000") this.attr({fill: "#000"}); 
    }
}

また、「刑務所」の箱に入れられた箱を再び拾うことができないようにすることもできます。これは、or関数内の位置のテストmove()またはstart()関数内での使用を使用c.undrag(f)して実行できstop()ます。

jsFiddleの例

window.onload = function() {
var nowX, nowY, R = Raphael("canvas", 500, 500),
    c = R.rect(200, 200, 40, 40).attr({
            fill: "hsb(.8, 1, 1)",
            stroke: "none",
            opacity: .5,
            cursor: "move"
        }),
    j = R.rect(0,0,100,100),
    // start, move, and up are the drag functions
    start = function () {
        // storing original coordinates
        this.ox = this.attr("x");
        this.oy = this.attr("y");
        this.attr({opacity: 1});
        if (this.attr("y") < 60 &&  this.attr("x") < 60)
            this.attr({fill: "#000"});        
    },
    move = function (dx, dy) {
        // move will be called with dx and dy
        if (this.attr("y") > 60 || this.attr("x") > 60)
            this.attr({x: this.ox + dx, y: this.oy + dy}); 
        else {
            nowX = Math.min(60, this.ox + dx);
            nowY = Math.min(60, this.oy + dy);
            nowX = Math.max(0, nowX);
            nowY = Math.max(0, nowY);            
            this.attr({x: nowX, y: nowY });
            if (this.attr("fill") != "#000") this.attr({fill: "#000"}); 
        }
    },
    up = function () {
        // restoring state
        this.attr({opacity: .5});
        if (this.attr("y") < 60 && this.attr("x") < 60)
            this.attr({fill: "#AEAEAE"});            
    };   
    // rstart and rmove are the resize functions;
    c.drag(move, start, up);
};​
于 2010-10-07T22:01:21.260 に答える