使用 fabric js 连接两个对象

Connect two objects using fabric js

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

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

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

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


}

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

您需要监听 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>

请注意,对于完整的解决方案,您需要能够取消 Add Child 并且您可能想要处理对象大小调整(当前,当您移动对象时该行会更新,但在您调整对象大小时不会)


Fiddle - http://jsfiddle.net/ctcdaxop/

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

添加子功能

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);
}

因为我们没有 canvas 引用,除非单击添加动画,因此必须在添加动画处理程序中附加处理程序

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();
}

Fiddle - http://jsfiddle.net/xvcyzh9p/