1

Good day everyone,

I was wondering if there was a way to detect if a fabric object is COMPLETELY inside another object?

I was looking at object.intersectsWithObject(object2) in the documentation but unfortunately, as soon as the object is completely inside object2, the function doesn't give back true anymore but false.

Has someone else had this problem? I am do not know at all how to do this. I have searched for the function in fabric.js. Can someone help?

    intersectsWithObject: function(other) {
  // extracts coords
  function getCoords(oCoords) {
    return {
      tl: new fabric.Point(oCoords.tl.x, oCoords.tl.y),
      tr: new fabric.Point(oCoords.tr.x, oCoords.tr.y),
      bl: new fabric.Point(oCoords.bl.x, oCoords.bl.y),
      br: new fabric.Point(oCoords.br.x, oCoords.br.y)
    };
  }
  var thisCoords = getCoords(this.oCoords),
      otherCoords = getCoords(other.oCoords),
      intersection = fabric.Intersection.intersectPolygonPolygon(
        [thisCoords.tl, thisCoords.tr, thisCoords.br, thisCoords.bl],
        [otherCoords.tl, otherCoords.tr, otherCoords.br, otherCoords.bl]
      );

  return intersection.status === 'Intersection';
}

Thank you already for your help Sebastian

1 Answer 1

4

If you want to know if an abject is completely inside another object you should use isContainedWithinObject:

isContainedWithinObject(other) → {Boolean}

§ Checks if object is fully contained within area of another object

Parameters:

Name : other
Type: Object

Description: Object to test

Source: fabric.js, line 12300

Returns: true if object is fully contained within area of another object

Type: Boolean

This is the source:

isContainedWithinObject: function(other) {
      var boundingRect = other.getBoundingRect(),
          point1 = new fabric.Point(boundingRect.left, boundingRect.top),
          point2 = new fabric.Point(boundingRect.left + boundingRect.width, boundingRect.top + boundingRect.height);

      return this.isContainedWithinRect(point1, point2);
    }

It works using the bounding box of the object you would test.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I was looking for every combination of 'inside' and 'inner' but didn't check 'within'. Thanks and sorry! Might help others in the future though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.