虽然不是100%准确,但对于大多数情况都是有效的。我使用了这里的算法:
function isUndefined(a) {
return a === undefined;
}
function doPolygonsIntersect (a, b) {
var polygons = [a, b];
var minA, maxA, projected, i, i1, j, minB, maxB;
for (i = 0; i < polygons.length; i++) {
var polygon = polygons[i];
for (i1 = 0; i1 < polygon.length; i1++) {
var i2 = (i1 + 1) % polygon.length;
var p1 = polygon[i1];
var p2 = polygon[i2];
var normal = { x: p2.y - p1.y, y: p1.x - p2.x };
minA = maxA = undefined;
for (j = 0; j < a.length; j++) {
projected = normal.x * a[j].x + normal.y * a[j].y;
if (isUndefined(minA) || projected < minA) {
minA = projected;
}
if (isUndefined(maxA) || projected > maxA) {
maxA = projected;
}
}
minB = maxB = undefined;
for (j = 0; j < b.length; j++) {
projected = normal.x * b[j].x + normal.y * b[j].y;
if (isUndefined(minB) || projected < minB) {
minB = projected;
}
if (isUndefined(maxB) || projected > maxB) {
maxB = projected;
}
}
if (maxA < minB || maxB < minA) {
console.log("polygons don't intersect!");
return false;
}
}
}
return true;
};
$('#r').click(function() {
var rota = Math.floor( Math.random() * 100 ),
rotb = Math.floor( Math.random() * 100 ),
pointsa = new Array(4),
pointsb = new Array(4);
$('#a').css('transform', 'rotateZ(' + rota + 'deg)');
$('#b').css('transform', 'rotateZ(' + rotb + 'deg)');
$('#a div').each(function(i) {
pointsa[i] = {x: parseInt($(this).offset().left), y: parseInt($(this).offset().top)};
});
$('#b div').each(function(i) {
pointsb[i] = {x: parseInt($(this).offset().left), y: parseInt($(this).offset().top)};
});
$('#s').val("intersection: " + doPolygonsIntersect(pointsb, pointsa).toString());
});
演示代码
我猜我的脚本并不是最好的方法,它基本上是在0到100度之间随机旋转,获取每个角落(使用div可以用数学方法计算位置,但我不行 :D)的x和y位置,并使用这些坐标运行算法。