以下是您所需内容的新版本,包括对多连接和删除的支持。
添加子功能
function addChildLine(options) {
canvas.off('object:selected', addChildLine);
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);
line.sendToBack();
fromObject.addChild = {
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);
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);
});
}
canvas.addChild = undefined;
}
function addChildMoveLine(event) {
canvas.on(event, function (options) {
var object = options.target;
var objectCenter = object.getCenterPoint();
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()
}
canvas.off('object:selected', addChildLine);
canvas.on('object:selected', addChildLine);
}
由于我们在“添加动画”被点击之前没有画布参考,因此处理程序必须附加在“添加动画”处理程序中。
window.newAnimation = function () {
canvas = new fabric.Canvas('canvas');
['object:moving', 'object:scaling'].forEach(addChildMoveLine)
}
删除对象时同时删除相关连线
window.deleteObject = function () {
var object = canvas.getActiveObject();
if (object.addChild) {
if (object.addChild.from)
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();
}
}
object.remove();
}
Fiddle - http://jsfiddle.net/xvcyzh9p/
canvas.connect
设置为 false 即可。 - potatopeelings