[英]jquery: sort 4 points to (top-left, top-right, bottom-right, bottom-left)
given: 2 arrays, each containing the coordinates of 4 points: 给定:2个数组,每个数组包含4个点的坐标:
point_array_a = [point_a_1_x, point_a_1_y, point_a_2_x, ..., point_a_4_y]
point_array_b = [point_b_1_x, ... ..., point_b_4_y]
task: 任务:
sort point_array_a such that in the end the points are listed in the following order: 对point_array_a进行排序,以便最后按以下顺序列出点:
point_array_a_sorted = [top-left_x, top_left_y, top-right_x, top-right_y, bottom-right_x, bottom_right_y, bottom-left_x, bottom_left_y]
sort point_array_b in the same way, such that point_a_k_l corresponds to point_b_k_l like in the beginning. 以相同的方式对point_array_b进行排序,以使point_a_k_l对应于开始时的point_b_k_l。
I'm afraid there is no simple algorithm for this. 恐怕没有简单的算法可以做到这一点。 But the following snippet will do the job (assuming that points with larger y-coordinates lie lower than points with lower y-coordinates):
但是下面的代码片段就可以了(假设y坐标较大的点低于y坐标较低的点):
var i, points = [], leftX = point_array_a[0], topY = point_array_a[1];
for (i = 0; i < 4; i++)
{
leftX = Math.min(leftX, point_array_a[i * 2]);
topY = Math.min(topY, point_array_b[i * 2]);
points.push([
[point_array_a[i * 2], point_array_a[i * 2 + 1]],
[point_array_b[i * 2], point_array_b[i * 2 + 1]]
]);
}
points.sort(function(first, second){
if (first[0][0] == leftX)
return first[0][1] == topY ? -1 : 1;
if (second[0][0] == leftX)
return second[0][1] == topY ? 1 : -1;
return first[0][1] < second[0][1] ? -1 : 1;
});
var point_array_a_sorted = [], point_array_b_sorted = [];
for (i = 0; i < 4; i++)
{
point_array_a_sorted.push(points[i][0][0], points[i][0][1]);
point_array_b_sorted.push(points[i][1][0], points[i][1][1]);
}
We leverage the existing Array.sort
function by feeding it just the right objects to compare and swap — pairs of points. 我们通过为现有的
Array.sort
函数提供正确的对象来进行比较和交换(成对的点)来利用它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.