 # Check is coordinates are within a shape boundaries

I have previously managed to check or detect if a click is inside a circle or a rectangle. Now I want to fill a shape with dots using Poisson-Disc algorithm. How can I detect if the current dot is within the bounds of a complex shape? Let’s take the below shape as an example:

``````function draw() {
background(220);

strokeWeight(1)
beginShape()
vertex(200,80)
bezierVertex(240,80,300,100,300,120)
vertex(300,150)
vertex(280,160)
vertex(280,170)
vertex(300,180)
vertex(300,220)
bezierVertex(300,240,240,260,200,260)
vertex(100,200)
vertex(100,150)
vertex(200,100)
endShape(CLOSE)
}
``````

I believe that if P5 is able to fill the shape, somehow P5 ‘knows’ with great accuracy (and pretty fast) what is inside and what is outside that shape. Is there a way we can access that info? If not, what would be the approach to check for a valid coordinate inside the shape?

One way is to check the color of the fill using get()

When the color is the fill color you are inside otherwise not.

This works even when you don’t fill the shape with a color: then you can draw the shape on an invisible canvas and fill it there and use get() there

1 Like

Here’s a Java method you can adapt for js:

``````	static final boolean pointInPoly(PShape s, PVector point) {

boolean within = false;
int j = s.getVertexCount() - 1;

for (int i = 0; i < s.getVertexCount(); i++) {
final PVector v = s.getVertex(i);
final PVector b = s.getVertex(j);
if (((v.y > point.y) != (b.y > point.y)) && (point.x < (b.x - v.x) * (point.y - v.y) / (b.y - v.y) + v.x)) {
within = !within;
}
j = i;
}
return within;
}
``````

p5 version … following Jeffrey Thompson’s collision detection book.