线与路径/多边形Fabric.js之间的交点

时间:2017-04-19 08:59:20

标签: javascript fabricjs

我们正在使用fabric.js在javascript上创建一个小应用程序,我们将形状放在画布上并用线条连接它们。有不同的形状,有些是用fabic.js' PolygonPath。线条从中心到中心,并在移动任一对象时正确更新。

这条线的末端还有一个小箭头。但是我想将这个形状放在线与物体相交的点上,所以它总是可见的。我已经尝试过使用fabric.js交叉函数,但除了知道两个对象是否相交,如intersection demo所示。

之后,我们无法理解它们的工作方式。

所以问题是:我怎样才能找到一个形状与一条线相交的点?

这是我们如何运作的概述:

var canvas = new fabric.Canvas('c');

function addChildMoveLine(options) {
  var object = options.target;
  var objectCenter = object.getCenterPoint();

  if (object.addChild) {
    if (object.addChild.from) {
      object.addChild.from.forEach(function(line) {
        var currentLineWidth = line.getStrokeWidth();
        line.set({
          'x1': objectCenter.x - currentLineWidth / 2,
          'y1': objectCenter.y - currentLineWidth / 2
        });
      });
      // Here we want to calculate the intersection between the object and the line.
    }
    if (object.addChild.to) {
      object.addChild.to.forEach(function(line) {
        var currentLineWidth = line.getStrokeWidth();
        line.set({
          'x2': objectCenter.x - currentLineWidth / 2,
          'y2': objectCenter.y - currentLineWidth / 2
        });
      });
      // Calculate the intersection on the other end.
    }
  }

  canvas.renderAll();
}

function addItem(x, y) {
  var circle = new fabric.Circle({
    radius: 50,
    fill: "#faa",
    scaleY: 0.5,
    originX: 'center',
    originY: 'center'
  });

  var text = new fabric.IText("text", {
    fontSize: 15,
    originX: 'center',
    originY: 'center'
  });

  var group = new fabric.Group([circle, text], {
    // any group attributes here
    left: x,
    top: y
  });

  canvas.add(group);
  canvas.renderAll();

  return group;
}

function makeLine(coords) {
  var line = new fabric.Line(coords, {
    fill: "#000",
    stroke:"#000",
    strokeWidth: 3,
    selectable: true
  });

  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);
  // to-object:
  toObject.addChild = {
    from: (toObject.addChild && toObject.addChild.from),
    to: (toObject.addChild && toObject.addChild.to) || []
  }
  toObject.addChild.to.push(line);

  return line;
}

canvas.on('object:moving', function(e){
  addChildMoveLine(e);
})

var fromObject = addItem(50, 100);
var toObject = addItem(300, 100);

var from = fromObject.getCenterPoint();
var to = toObject.getCenterPoint();
var coords = [from.x, from.y - 3 / 2, to.x, to.y - 3 / 2];
var line = makeLine(coords);
canvas.add(line);
line.sendToBack();

JSfiddle与exxampl合作。

非常感谢任何帮助。

编辑澄清问题并添加代码和JSfiddle。

0 个答案:

没有答案