Sophie D
Sophie D

Reputation: 465

FabricJS check if image is inside of a polygon

Is there a way to check if an object (in my example image) is inside of another Object (in my example a polygon). I created a small jsfiddle: http://jsfiddle.net/onot3w11/

Here is my code, basically adding a polygon and an image and testing, if the image is inside of the polygon:

/*_________adding shapes____*/
var imgInstance = new fabric.Image(imgElement, {
  left: 100,
  top: 100,
  angle: 30,
  opacity: 0.85,            
  width: 150,
  height: 150,
});


var pol2 = new fabric.Polygon([
  {x: 300, y: 50},
  {x: 300, y: 250},
  {x: 150, y: 250},
  {x: 150, y: 50} ], {
    left: 20,
    top: 100,
    angle: 0,
    fill: 'grey',
    opacity: 0.1
  }
);
canvas.add(pol2);
canvas.add(imgInstance);

/*_________testing if image is inside polygon____*/
console.log(imgInstance.isContainedWithinObject(pol2));

The christmas tree is inside of the polygon, but because of its border, the "isContainedWithinObject" returns "false" in the console. There is another function, which only returns true, if the two objects intersect with each other (but will return false if an object is completely within another object http://fabricjs.com/intersection). Maybe I could combine both funtions to get what i want, but I hope that there might be an easier solution.

I tried around a little bit and think the best solution if something is inside of an object is to get the center of it and check if this point is contained in the object. Is there a way to get the center of an image?

Upvotes: 1

Views: 1375

Answers (1)

neopheus
neopheus

Reputation: 665

Like this issue: https://github.com/kangax/fabric.js/issues/601

Small Idea: Your image is an SVG. Instead of fabric.Image, use fabric.loadSVGFromURL.

Upvotes: 1

Related Questions