1

通过阅读有关包含点 ( http://fabricjs.com/docs/symbols/fabric.Canvas.html#containsPoint ) 的 Fabric 文档,它指出:

Applies one implementation of 'point inside polygon' algorithm
Parameters:
e
{ Event } event object
target
{ fabric.Object } object to test against
Returns:
{Boolean} true if point contains within area of given object

因此,基于此,我尝试遍历组内的所有对象,如果 containsPoint 返回 true,则选择该对象。

但它总是返回 false;

canvas.on('object:selected',function(o,i) {

    console.log(o)

    if ( o.target.isType('group') ) {
        o.target.forEachObject(function(child) {
            child.setCoords();
            //always false
            console.log(canvas.containsPoint(o.e, child) );
        });
    }
})

这是 jsFiddle - 有什么想法吗? http://jsfiddle.net/LNt2g/1/

4

2 回答 2

2

解决了!有点令人费解,但它有效。我必须根据组和子对象的尺寸/位置专门计算开始和结束 x/y。

canvas.on('mouse:down', function(options) {

    if (options.target) {

        var thisTarget = options.target; 
        var mousePos = canvas.getPointer(options.e);

        if (thisTarget.isType('group')) {

            var groupPos = {
                x: thisTarget.left,
                y: thisTarget.top
            }

            thisTarget.forEachObject(function(object,i) {

                var objectPos = {
                    xStart: (groupPos.x - (object.left*-1) )  - (object.width / 2),
                    xEnd: (groupPos.x - (object.left*-1)) + (object.width / 2),
                    yStart: (groupPos.y - (object.top*-1)) - (object.height / 2),
                    yEnd: (groupPos.y - (object.top*-1)) + (object.height / 2)
                }

                if (mousePos.x >= objectPos.xStart && mousePos.x <= (objectPos.xEnd)) {

                    if (mousePos.y >= objectPos.yStart && mousePos.y <= objectPos.yEnd) {
                        console.log(objectPos);
                        console.log('Hit!',object);
                    }
                }

            });   
        }    

    }

});  

这里更新的小提琴:http: //jsfiddle.net/LNt2g/4/

于 2013-03-04T20:50:45.840 回答
0

这里的工作示例:

fabric.util.object.extend(fabric.Object.prototype, {
getAbsoluteCenterPoint: function() {
  var point = this.getCenterPoint();
  if (!this.group)
    return point;
  var groupPoint = this.group.getAbsoluteCenterPoint();
  return {
    x: point.x + groupPoint.x,
    y: point.y + groupPoint.y
  };
},
containsInGroupPoint: function(point) {
  if (!this.group)
    return this.containsPoint(point);

  var center = this.getAbsoluteCenterPoint();
  var thisPos = {
      xStart: center.x - this.width/2,
      xEnd: center.x + this.width/2,
      yStart: center.y - this.height/2,
      yEnd: center.y + this.height/2
  }

  if (point.x >= thisPos.xStart && point.x <= (thisPos.xEnd)) {
      if (point.y >= thisPos.yStart && point.y <= thisPos.yEnd) {
          return true;
      }
  }
  return false;
}});

http://plnkr.co/edit/4rlRPxwIqFIOvjrVYx8z?p=preview

感谢@mindwire22 的回答https://groups.google.com/d/msg/fabricjs/XfFMgo1Da7U/Hv7LsYa9hMEJ

于 2016-03-12T10:41:59.163 回答