Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //lines are represented in ax+by+c = 0 form in an array [a,b,c]. Coordinates in [x,y]
- var coords = [
- [1, 0],
- [1, 1],
- [0, 0.5],
- [-1, 1],
- [-1, 0]
- ];
- var point = [0, 0.6];
- function polygon() {
- for (var i = 0, n = coords.length; n > 3; n = coords.length) {
- //if the i+1 point(point next to current anchor) is convex, then it is our new anchor point.
- var array = [coords[(i + n - 1) % n], coords[i % n], coords[(i + 1) % n], coords[(i + 2) % n], coords[(i + 3) % n]];
- if (isConvex(array)) {
- i++;
- }
- // checks if given point is inside the triangle formed by i(anchor), i+1 and i+2. If not, i+1th point is removed.
- var array = [coords[i % n], coords[(i + 1) % n], coords[(i + 2) % n]];
- if (inTri(array)) {
- return true;
- } else {
- coords.splice(i + 1, 1);
- }
- }
- return (inTri(coords) ? true : false);
- }
- //checks if same side or on the line
- function sameSide(line, pointA, pointB) {
- if ((pointA[0] * line[0] + line[1] * pointA[1] + line[2]) * (pointB[0] * line[0] + line[1] * pointB[1] + line[2]) >= 0) {
- return true;
- } else {
- return false;
- }
- }
- function inTri(vertices) {
- for (var i = 0; i < 3; i++) {
- if (!sameSide(findLine(vertices[i], vertices[(i + 1) % 3]), point, vertices[(i + 2) % 3])) {
- return false;
- }
- }
- // this one handles zero area triangles
- var length1 = Math.sqrt(Math.pow((vertices[0][0] - vertices[1][0]), 2) + Math.pow((vertices[0][1] - vertices[1][1]), 2));
- var length2 = Math.sqrt(Math.pow((vertices[0][0] - vertices[2][0]), 2) + Math.pow((vertices[0][1] - vertices[2][1]), 2));
- var length3 = Math.sqrt(Math.pow((vertices[1][0] - vertices[2][0]), 2) + Math.pow((vertices[1][1] - vertices[2][1]), 2));
- if (length1 + length2 == length3 || Math.abs(length1 - length2) == length3) {
- return false;
- }
- return true;
- }
- // finds out whether the middle element of a five element array is convex
- function isConvex(vertices) {
- if (sameSide(findLine(vertices[2], vertices[3]), vertices[4], vertices[1])) {
- return false;
- }
- if (sameSide(findLine(vertices[2], vertices[1]), vertices[0], vertices[3])) {
- return false;
- }
- return true;
- }
- function findLine(pointA, pointB) {
- var a = pointB[1] - pointA[1];
- var b = pointA[0] - pointB[0];
- var c = -a * pointA[0] - b * pointA[1];
- return [a, b, c];
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement