2013-03-04 130 views
1

集團從閱讀的文檔,面料上ContainsPoint(http://fabricjs.com/docs/symbols/fabric.Canvas.html#containsPoint),它規定:使用ContainsPoint選擇對象在

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/

回答

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/

+0

這是行不通的。 – 2015-10-26 11:38:58

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 answerhttps://groups.google.com/d/msg/fabricjs/XfFMgo1Da7U/Hv7LsYa9hMEJ