Continuing on my journey of learning the in's and out's of HTML5's Canvas, I found myself needing to detect whether a point on my canvas was within the region of one of my multiple objects already drawn on the canvas.
At first I thought I was stuck with the only option of having to loop through each of the objects, calculating all of the co-ordinates that the object covers and then seeing if any of them tally up with another my point of interest. I hope that makes sense, it definitely took me a while to even come up with that solution. However, as I began down this route I thought there must be a better way, something I'm missing.
After some googling, I came across isPointInPath(), a function within the Canvas API which, in short, allows you to check if a co-ordinate (passed into the function) is within the current path being drawn. Perfect! The only issue is that I have been drawing my object's through the use of methods such as .drawRect() which, from what I could tell anyway, could not be used within a path. This therefore meant that I needed to redraw my object's.
In the code below, I check to see if a point is within the current path, and therefore change the colour of the object I am about to draw. This is it in it's simplest form, but you could use it to do alot more, especially when bringing mouse interactions into a Canvas piece.
context.beginPath();
context.moveTo(100, 100);
context.lineTo(200, 100);
context.lineTo(200, 200);
context.lineTo(100, 200);
context.fillStyle = "rgb(0, 0, 0)";
context.fill();
if(context.isPointInPath(250, 250)) {
var blockColour = "rgb(255, 0, 0)";
}
else {
var blockColour = "rgb(0, 255, 0)";
}
context.closePath();
context.fillStyle = blockColour;
context.fillRect(250, 250, 5, 5);
You can also see though that I am drawing a 5x5 rectangle, starting at
the co-ordinate I passed into the isPointInPath function. This means
though that whilst the starting point is not in the path, another point
within the rectangle could be. This leaves me the next challenge to see
if I can check if any point within a path is within a point within
another path. I do like to give myself challenges, don't I?
In the following demos, you can see an example of the above code in action; a point being within the path and another point being outside the path.