我正在为我的网络应用程序使用 rapaeljs。我想设置对象的可放置边界。对象可以在可放置区域中移动。一旦物体进入可放置区域,该物体就应该没有出路。
问问题
18184 次
1 回答
63
Raphael 通过.drag()
. 以下列形式使用它,element.drag(start, move, up);
其中 3 个参数是对您编写的函数的 3 个函数引用,这些函数分别处理 mousedown、movement 和 mouseup 事件。
注意this.ox
和this.oy
是如何用于存储起始位置的 和dx
是如何dy
用于运动的。
下面实现了一个框的拖放。盒子总是可以移动的,但是一旦它在“监狱”盒子里,就不能再移出来了。当盒子进入监狱时,颜色会立即改变,向用户发出功能已经改变的信号。
这是通过调整框的位置来实现的,Math.min()
然后将其添加到当前位置:Math.max()
dx
dy
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 回答