使用fabric js连接两个对象

时间:2015-08-29 23:54:29

标签: javascript canvas fabricjs

我目前有一个画布应用程序,我可以在其中添加对象(形状)。这是我的FIDDLE。您基本上单击将初始化画布的新模拟,然后您可以添加圆或矩形。

我正在尝试添加名为"添加子项"的功能您可以在其中单击某个对象(形状),然后单击添加子项并添加另一个对象(形状),它们都与一条线链接。类似于DEMO的东西。

我认为此功能的pesudo代码如下所示:

function addChild(){

    get getActiveObject
    draw a line/arrow connect it with getActiveObject
    draw object connected with line
    should be able to move it / strecth it around


}

我想知道这是否可行以及如何开始。请指教。

2 个答案:

答案 0 :(得分:3)

您需要侦听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会跟踪是否单击了Add Child(并且应该添加到按钮的onclick),以便下一个object:selected可以绘制线(否则它只是跟踪当前选定的元素)

<button onClick="addChild()">Add Child</button>

请注意,对于完整的解决方案,您需要能够取消添加子项,并且您可能希望处理对象大小调整(当前移动对象时行更新但是当您调整对象大小时不行)

小提琴 - http://jsfiddle.net/ctcdaxop/

答案 1 :(得分:3)

这是您正在寻找的新版本,包括支持多个连接和删除

添加子功能

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/