以下代码的目的是拖动两个矩形中的任何一个并使它们与线连接。但是,正如您在jsfiddle中看到的那样,该线移动到其他位置。这段代码出了什么问题?
这是HTML
<div id="canvas"></div>
这是javascript
window.onload = function() {
var paper = Raphael("canvas", 600, 600);
var rect1 = paper.rect(100, 100, 100, 100 ).attr({"fill":"blue"});
var rect2 = paper.rect(400, 100, 100, 100 ).attr({"fill":"green"});
rect1.node.id = "rect1";
rect2.node.id = "rect2";
var x1=200, y1=150, x2=400, y2=150;
var line = paper.path(['M', x1, y1, 'L', x2, y2]);
var start = function () {
// storing original coordinates
this.ox = this.attr("x");
this.oy = this.attr("y");
},
move = function (dx, dy) {
// move will be called with dx and dy
this.attr({x: this.ox + dx, y: this.oy + dy});
if ( this.node.id == "rect1" ) {
x1 += dx;
y1 += dy;
}
else if ( this.node.id == "rect2" ) {
x2 += dx;
y2 += dy;
}
line.attr("path", ['M', x1, y1, 'L', x2, y2]);
},
up = function () {
// restoring state
};
rect1.drag(move, start, up);
rect2.drag(move, start, up);
};
答案 0 :(得分:2)
那么,
您可以使用
获取方块的边界框Element.getBBox();
方法并从
计算路径值 if ( this.node.id == "rect1" ) {
var bb=rect1.getBBox();
x1=bb.x2;
y1=bb.y+(bb.height/2);
}
else if ( this.node.id == "rect2" ) {
var bb2=rect2.getBBox();
x2=bb2.x;
y2=bb2.y+(bb2.height/2);
}
答案 1 :(得分:0)
编辑:当两者都被移动时原始版本不起作用,我更新了使用this.ox和this.oy属性,这些属性很有用。小提琴也完全更新了。
dx和dy与初始位置相对,否则它们将始终具有-1到1范围内的值,以指示每次移动时的值。这意味着您的原始x1,y1 ......等越来越远。相反,你应该保持初始位置不变,只需通过dx,dy修改它们:
if ( this.node.id == "rect1" ) {
n_x1 = this.ox + dx + 100;
n_y1 = this.oy + dy + 50;
}
else if ( this.node.id == "rect2" ) {
n_x2 = this.ox + dx;
n_y2 = this.oy + dy + 50;
}
line.attr("path", ['M', n_x1, n_y1, 'L', n_x2, n_y2]);