javascript polygon intersection

痞子三分冷 提交于 2019-11-30 18:47:04

问题


I have used the code in the following : http://www.amphibian.com/blogstuff/collision.html. in the html test file I have changed the the first triangle to

triangle1.addPoint({"x":-20, "y":-20});
triangle1.addPoint({"x":-20, "y":20});
triangle1.addPoint({"x":20, "y":20});
triangle1.addPoint({"x":20, "y":10});
triangle1.addPoint({"x":10, "y":10});
triangle1.addPoint({"x":10, "y":-20});

now when I move the other triangle with inside this shape before crossing it gives me wrongly intersection. Any idea where could be the problem?


回答1:


All right, I set up a fiddle for anyone else wanting to play with this. Here are the results:

The script makes use of the Separating Axis Theorem or (as Wikipedia calls it) Hyperplane separation theorem, as explained in the source of polygon.js:

/*
 *  To detect intersection with another Polygon object, this
 *  function uses the Separating Axis Theorem. It returns false
 *  if there is no intersection, or an object if there is. The object
 *  contains 2 fields, overlap and axis. Moving the polygon by overlap
 *  on axis will get the polygons out of intersection.
 */
Polygon.prototype.intersectsWith = function(other) {

This theorem only applies to convex polygons. Your shape is not convex as it has a "dent" in it. That's why the script incorrectly reports that the shapes are intersecting. If you need to make it work with concave shapes, you'll have to make it first split the concave shape up in separate convex parts and then apply the theorem to all individual parts. Obviously, this makes the script more complex as you need to iterate over the cross product of the concave parts of two shapes.




回答2:


Here is my not too complicated implementation of finding the intersection polygon of two polygons.

It works for convex and concave polygons, but not for complex (self-intersecting) polygons. Algorithm is fairly similar to the one presented in Margalit & Knott.

Its complexity is about 4*n1*n2, where n1 and n2 are numbers of vertices in polygons whose intersection is being calculated.

It is a single standalone .js file. A 'Polygon' is regarded any javascript array of 2D Points. A 'Point' is any javascript object with x and y numeric properties.

Implementing the Union functionality on top of existing one should not be a problem and I will do it probably soon.

Intersection of 2D polygons



来源:https://stackoverflow.com/questions/10838389/javascript-polygon-intersection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!