你需要聆听object:selected
事件添加连接线和object:moving
更新线坐标的事件。
// function for drawing a line
function makeLine(coords) {
return new fabric.Line(coords, {
fill: 'red',
stroke: 'red',
strokeWidth: 5,
selectable: false
});
}
var canvas;
window.newAnimation = function(){
canvas = new fabric.Canvas('canvas');
var selectedElement = null;
canvas.on('object:selected', function(options) {
// we are doing t oadd a connection
if (canvas.connect) {
canvas.connect = false;
var from = selectedElement.getCenterPoint();
var to = options.target.getCenterPoint();
var line = makeLine([from.x, from.y, to.x, to.y]);
canvas.add(line);
// these take care of moving the line ends when the object moves
selectedElement.moveLine = function() {
var from = selectedElement.getCenterPoint();
line.set({ 'x1': from.x, 'y1': from.y });
};
options.target.moveLine = function() {
var to = options.target.getCenterPoint();
line.set({ 'x2': to.x, 'y2': to.y });
};
}
selectedElement = options.target;
});
canvas.on('object:moving', function(e) {
e.target.moveLine();
canvas.renderAll();
});
}
window.addChild = function() {
canvas.connect = true;
}
window.addChild 会跟踪“添加子项”是否被单击(并且应该添加到按钮的 onclick 中),以便下一个object:selected
可以画线(否则它只是跟踪当前选定的元素)
<button onClick="addChild()">Add Child</button>
请注意,对于完整的解决方案,您需要能够取消“添加子项”,并且您可能想要处理对象大小调整(当前,当您移动对象时,该行会更新,但在调整对象大小时不会更新)
小提琴 -http://jsfiddle.net/ctcdaxop/ http://jsfiddle.net/ctcdaxop/