这是您正在寻找的新版本,包括对多个连接和删除的支持
添加子功能
function addChildLine(options) {
canvas.off('object:selected', addChildLine);
// add the line
var fromObject = canvas.addChild.start;
var toObject = options.target;
var from = fromObject.getCenterPoint();
var to = toObject.getCenterPoint();
var line = new fabric.Line([from.x, from.y, to.x, to.y], {
fill: 'red',
stroke: 'red',
strokeWidth: 5,
selectable: false
});
canvas.add(line);
// so that the line is behind the connected shapes
line.sendToBack();
// add a reference to the line to each object
fromObject.addChild = {
// this retains the existing arrays (if there were any)
from: (fromObject.addChild && fromObject.addChild.from) || [],
to: (fromObject.addChild && fromObject.addChild.to)
}
fromObject.addChild.from.push(line);
toObject.addChild = {
from: (toObject.addChild && toObject.addChild.from),
to: (toObject.addChild && toObject.addChild.to) || []
}
toObject.addChild.to.push(line);
// to remove line references when the line gets removed
line.addChildRemove = function () {
fromObject.addChild.from.forEach(function(e, i, arr) {
if (e === line)
arr.splice(i, 1);
});
toObject.addChild.to.forEach(function (e, i, arr) {
if (e === line)
arr.splice(i, 1);
});
}
// undefined instead of delete since we are anyway going to do this many times
canvas.addChild = undefined;
}
function addChildMoveLine(event) {
canvas.on(event, function (options) {
var object = options.target;
var objectCenter = object.getCenterPoint();
// udpate lines (if any)
if (object.addChild) {
if (object.addChild.from)
object.addChild.from.forEach(function (line) {
line.set({ 'x1': objectCenter.x, 'y1': objectCenter.y });
})
if (object.addChild.to)
object.addChild.to.forEach(function (line) {
line.set({ 'x2': objectCenter.x, 'y2': objectCenter.y });
})
}
canvas.renderAll();
});
}
window.addChild = function () {
canvas.addChild = {
start: canvas.getActiveObject()
}
// for when addChild is clicked twice
canvas.off('object:selected', addChildLine);
canvas.on('object:selected', addChildLine);
}
由于我们没有画布引用,除非单击添加动画,处理程序必须附加到添加动画处理程序中
window.newAnimation = function () {
canvas = new fabric.Canvas('canvas');
// we need this here because this is when the canvas gets initialized
['object:moving', 'object:scaling'].forEach(addChildMoveLine)
}
删除对象时删除行
window.deleteObject = function () {
var object = canvas.getActiveObject();
// remove lines (if any)
if (object.addChild) {
if (object.addChild.from)
// step backwards since we are deleting
for (var i = object.addChild.from.length - 1; i >= 0; i--) {
var line = object.addChild.from[i];
line.addChildRemove();
line.remove();
}
if (object.addChild.to)
for (var i = object.addChild.to.length - 1; i >= 0; i--) {
var line = object.addChild.to[i];
line.addChildRemove();
line.remove();
}
}
// from original code
object.remove();
}
小提琴 - http://jsfiddle.net/xvcyzh9p/