我的 Canvas 上有两个矩形,现在我希望如果我将其中一个拖到另一个之上,它们就会对齐在一起。我想我需要使用 set() 但不知道如何使用。这是我到目前为止所得到的。
$(document).ready(function(){
var paper = Raphael(20, 20, 5000, 5000);
var rect1 = paper.rect(50, 50, 50, 50).attr({
fill: "hsb(.8, 1, 1)",
stroke: "none",
opacity: .5,
});
var rect2 = paper.rect(50, 50, 50, 50).attr({
fill: "hsb(.8, 1, 1)",
stroke: "none",
opacity: .5,
});
var rectStart = function() {
this.ox = this.attr("x");
this.oy = this.attr("y");
this.attr({opacity: 1});
},
rectMove = function(dx, dy) {
this.attr({x: this.ox + dx, y: this.oy + dy});
},
rectUp = function(){
this.attr({opacity: .5});
};
rect1.drag(rectMove, rectStart, rectUp);
rect2.drag(rectMove, rectStart, rectUp);
最佳答案
您只需在 rectUp
方法中编写逻辑即可。
这是工作 fiddle
var paper = Raphael(20, 20, 5000, 5000);
var rect1 = paper.rect(50, 50, 50, 50).attr({
fill: "hsb(.8, 1, 1)",
stroke: "none"
});
rect1.track_x = 50;
rect1.track_y = 50;
var rect2 = paper.rect(150, 50, 50, 50).attr({
fill: "#aa9988",
stroke: "none"
});
rect2.track_x = 150;
rect2.track_y = 50;
function rectStart() {
}
function rectMove(dx, dy) {
this.attr({x: this.track_x + dx, y: this.track_y + dy});
}
function rectUp() {
this.track_x = this.attr("x");
this.track_y = this.attr("y");
var currentDragRect, idleRect;
if(this == rect1) {
currentDragRect = rect1;
idleRect = rect2;
} else {
currentDragRect = rect2;
idleRect = rect1;
}
/*
r11 r12 currentDragRect
r21 r22 idleRect
*/
//r11 <= r22 && r21 <= r12
//50 is width and height
if( (currentDragRect.track_x <= (idleRect.track_x + 50)) &&
(idleRect.track_x <= (currentDragRect.track_x + 50)) ) {
if( (currentDragRect.track_y <= (idleRect.track_y + 50)) &&
(idleRect.track_y <= (currentDragRect.track_y + 50)) ) {
//p.translate(300, 100);
alert('Done ' + idleRect.track_x);
currentDragRect.attr({x: idleRect.track_x, y: idleRect.track_y});
//currentDragRect.transform('t' + idleRect.track_x + ','+ idleRect.track_y);
}
}
}
rect1.drag(rectMove, rectStart, rectUp);
rect2.drag(rectMove, rectStart, rectUp);
我还尝试使用 Element.onDragOver但它didnt work正如预期的那样。正如 SO answer 中所述跟踪坐标将有助于解决此类问题。
关于javascript - 如何创建两个元素的集合: Raphael,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32689138/