我已经为 Raphael JS 创建了一个插件。它基本上允许您调用
paper.connect(obj1,obj2,colour)
这将在两个对象之间绘制一条线,并在对象动画时保持该线。 这是我迄今为止想出的东西。它可以工作,但性能不太好,您有什么其他建议来实现同样的功能吗?
这将在两个对象之间绘制一条线,并在对象动画时保持该线。 这是我迄今为止想出的东西。它可以工作,但性能不太好,您有什么其他建议来实现同样的功能吗?
Raphael.fn.connect = function(obj1, obj2, colour) {
// list of paths each object has
obj1.connections = []
obj2.connections = []
// get the bounding box of each object
var box1 = obj1.getBBox()
var box2 = obj2.getBBox()
// create a line/path from object 1 to object 2
var p = this.path("M" + (box1.x + box1.width / 2) + ","
+ (box1.y + box1.height / 2) + "L" + (box2.x + box2.width / 2)
+ "," + (box2.y + box2.height / 2))
// adjust attributes of the path
p.attr({
stroke : colour,
"stroke-linecap" : "round",
"stroke-opacity" : Math.max(obj1.attr('opacity'), obj2.attr('opacity'))
})
// set the start and end element for this path
p.startElement = obj1;
p.endElement = obj2;
// add the path to each of the object
obj1.connections.push(p)
obj2.connections.push(p)
// mark each object as being connected
obj1.connected = true;
obj2.connected = true;
// listen for the Raphael frame event
eve.on("raphael.anim.frame.*", function(obj) {
// if the object the frame event is fired on is connected
if (this.connected) {
// for each connection on this object
for ( var c in this.connections) {
var path = this.connections[c]; // temp path
var b1 = path.startElement.getBBox(); // get the current
// location of start
// element
var b2 = path.endElement.getBBox();// get the current location
// of end element
// move the path to the new locations
path.attr({
path : "M " + (b1.x + b1.width / 2) + " "
+ (b1.y + b1.height / 2) + "L "
+ (b2.x + b2.width / 2) + " "
+ (b2.y + b2.height / 2),
opacity : Math.max(path.startElement.attr('opacity'),
path.endElement.attr('opacity'))
});
}
}
});
}
我并不确定这是否是最佳方法,但这是我第一次使用Raphael,所以我只是根据阅读Raphael源代码完成了所有操作...
.connect()
会导致第一次连接断开(因为obj{1|2}.connections
被重置)。您可以通过将前几行更改为if (!obj1.connections) obj1.connections = []
和if (!obj2.connections) obj2.connections = []
来解决此问题。 - Dan