Isak Berglind
Isak Berglind

Reputation: 197

Figure out if point is inside of shape

I'm hacking on a vector car game in javascript and html canvas. The point is that you click on of the blue squares and the car goes there - simple!

The outer and inner borders are two arrays of xy points that i've drawn out on the canvas

I've come to the point where i need to figure out if the car is on the course or not.

I've tried a bunch of different things, but just cant get this to work. Its the diagonal lines that makes my head hurt.

Can someone point me in the right direction how i would go about doing this? You don't need to post any code, just some guidelines on which approach to take and how to calculate.

enter image description here

Upvotes: 1

Views: 1308

Answers (2)

treeno
treeno

Reputation: 2600

You could use CanvasRenderingContext2D#isPointInPath() to check wether a Point is on the track or not.

https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/isPointInPath

To do so you might need to refactor your Code in a manner so that the track is drawn as a separate path. Additionally, isPointInPath() must be called right after the path has been drawn and before any furthor path is drawn, because isPointInPath() is applied to the current path on the state-stack.

Upvotes: 1

user1693593
user1693593

Reputation:

You can use a Path2D object combined with even-odd fill-rule and isPointInPath(). This allow you to define the test-path once and not have concerns about what you draw on the main context. If your path changes simply redefine the path object accordingly.

First define the two paths on the path object (not context). Separate them using moveTo() for the second path. You may want to use closePath() as well if you plan to stroke (for testing this will be implicit).

Test using the path and the even-odd fill rule:

if (ctx.isPointInPath(path, x, y, "evenodd")) { /* inside */ };

var ctx = c.getContext("2d");
var path = new Path2D();
path.arc(75, 75, 74, 0, 6.28);  // replace with the polygons
path.closePath();
path.moveTo(75 + 40, 75);
path.arc(75, 75, 40, 0, 6.28);
path.closePath();

ctx.stroke(path);
ctx.globalCompositeOperation = "copy";

window.onmousemove = function(e) {
  ctx.strokeStyle = ctx.isPointInPath(path, e.clientX, e.clientY, "evenodd") ? "red" : "#000";
  ctx.stroke(path);
};
html, body {margin:0}
<canvas id=c></canvas>

Upvotes: 2

Related Questions